How to use strings in C language?
In the C language, although there is no built-in string type, you can use character arrays to represent strings. Here are several common ways to use strings:
- Store the string in a character array.
char str[10]; // 定义一个长度为10的字符数组
strcpy(str, "Hello"); // 将字符串复制到字符数组中
printf("%s\n", str); // 输出字符串
- Store strings using character pointers.
char *str; // 定义一个字符指针
str = "Hello"; // 指针指向字符串常量
printf("%s\n", str); // 输出字符串
- Manipulate strings using character arrays and library functions related to strings, such as strcpy, strcat, strlen, etc.
char str1[10] = "Hello";
char str2[10] = "World";
char str3[20]; // 定义一个足够大的字符数组来存储连接后的字符串
strcpy(str3, str1); // 将str1复制到str3中
printf("%s\n", str3); // 输出Hello
strcat(str3, str2); // 将str2连接到str3后面
printf("%s\n", str3); // 输出HelloWorld
printf("%d\n", strlen(str3)); // 输出字符串的长度
Please make sure that the target character array is large enough to prevent overflow when using string-related functions.