How to use strings in C language?
In C language, character arrays can be used to represent strings. Here are some common string operation functions and their usage:
- Declaration and assignment of strings:
char str[20]; // 声明一个长度为20的字符数组来存储字符串
strcpy(str, "Hello, World!"); // 将字符串赋值给字符数组
- Output of strings:
printf("%s\n", str); // 使用%s格式化字符串进行输出
- Comparison of strings:
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2); // 按字典顺序比较两个字符串
if (result == 0) {
printf("两个字符串相等\n");
} else if (result < 0) {
printf("%s在%s之前\n", str1, str2);
} else {
printf("%s在%s之后\n", str1, str2);
}
- String concatenation:
char str1[20] = "Hello";
char str2[] = "World";
strcat(str1, str2); // 将str2拼接到str1的末尾
printf("%s\n", str1); // 输出拼接后的字符串
- Length of the string:
char str[] = "Hello";
int len = strlen(str); // 获取字符串的长度
printf("字符串长度为:%d\n", len);
- Copying strings:
char str1[20] = "Hello";
char str2[20];
strcpy(str2, str1); // 将str1复制到str2
printf("%s\n", str2); // 输出复制后的字符串
It is important to ensure that the size of the character array used to represent a string is large enough to accommodate the string being stored in order to prevent array out-of-bound errors.