1. strcpy - 复制字符串
strcpy(destination, source)
函数用于将 source
字符串复制到 destination
字符串。这会包括终止的空字符 '\0'
。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main() {
char src[40] = "This is source";
char dest[100];
strcpy(dest, src);
printf("%s", dest);
return 0;
}
2. strcat - 连接字符串
strcat(destination, source)
函数将 source
字符串连接到 destination
字符串的末尾,并覆盖 destination
的终止空字符 '\0'
,最后再添加一个新的终止空字符。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main() {
char src[50], dest[50];
strcpy(src, "This is source");
strcpy(dest, "This is destination");
strcat(dest, src);
printf("%s", dest);
return 0;
}
3. strlen - 计算字符串长度
strlen(str)
函数计算字符串 str
的长度,直到但不包括终止的空字符。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main() {
char myString[] = "Hello, world!";
printf("字符串长度: %lld", strlen(myString));
return 0;
}
4. strcmp - 比较两个字符串
strcmp
函数的作用是逐个字符比较两个字符串,直到遇到第一个不同的字符或遇到字符串的终止符 \0
为止。
- 使用
strcmp
函数时,确保两个字符串都是以\0
结尾的,否则可能会导致未定义行为。 - 由于
strcmp
函数是根据ASCII值进行比较的,所以它是区分大小写的。如果需要进行不区分大小写的比较,可以使用strcasecmp
或_stricmp
函数(这取决于编译器和平台)。
int strcmp<