在C語言中,字符串函數可以通過以下兩種方式定義:
#include <stdio.h>
// 字符串長度
int my_strlen(char str[]) {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}
// 字符串復制
void my_strcpy(char dest[], char src[]) {
int i = 0;
while (src[i] != '\0') {
dest[i] = src[i];
i++;
}
dest[i] = '\0';
}
// 字符串連接
void my_strcat(char dest[], char src[]) {
int dest_len = my_strlen(dest);
int i, j = 0;
for (i = dest_len; src[j] != '\0'; i++, j++) {
dest[i] = src[j];
}
dest[i] = '\0';
}
int main() {
char str1[100] = "Hello";
char str2[100] = "World";
printf("str1 length: %d\n", my_strlen(str1));
my_strcpy(str1, str2);
printf("str1 after copy: %s\n", str1);
my_strcat(str1, str2);
printf("str1 after concatenation: %s\n", str1);
return 0;
}
#include <stdio.h>
// 字符串長度
int my_strlen(char *str) {
int len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}
// 字符串復制
char* my_strcpy(char *dest, char *src) {
char *p = dest;
while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
return p;
}
// 字符串連接
char* my_strcat(char *dest, char *src) {
char *p = dest;
while(*dest != '\0') {
dest++;
}
while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
return p;
}
int main() {
char str1[100] = "Hello";
char str2[100] = "World";
printf("str1 length: %d\n", my_strlen(str1));
my_strcpy(str1, str2);
printf("str1 after copy: %s\n", str1);
my_strcat(str1, str2);
printf("str1 after concatenation: %s\n", str1);
return 0;
}
無論使用字符數組還是指針,都可以實現相同的功能。但是需要注意指針的使用需要更謹慎,避免指針操作超出字符串的范圍。