How are string arrays used in the C language?
In C language, a string array typically refers to a character array used to store a series of characters.
In C language, strings are stored and manipulated using character arrays. Strings in C end with a null character ‘\0’, so the size of the character array should be greater than or equal to the length of the string plus one.
Below are some common methods for using character arrays:
- Declare and initialize a character array:
char str1[10]; // 声明一个大小为10的字符数组
char str2[10] = "Hello"; // 声明一个大小为10的字符数组,并初始化为"Hello"
char str3[] = "World"; // 根据字符串长度自动确定字符数组大小,并初始化为"World"
- Assigning and copying character arrays:
strcpy(str1, str2); // 将字符串从str2复制到str1
strncpy(str1, str2, n); // 将str2的前n个字符拷贝到str1
- Comparison of character arrays:
strcmp(str1, str2); // 比较str1和str2的大小,返回比较结果(0代表相等)
strncmp(str1, str2, n); // 比较str1和str2的前n个字符的大小,返回比较结果
- Concatenation of character arrays.
strcat(str1, str2); // 将str2连接到str1的末尾
strncat(str1, str2, n); // 将str2的前n个字符连接到str1的末尾
- The length of the character array:
strlen(str1); // 返回str1中字符的个数(不包括结束符'\0')
- Input and output of character arrays:
printf("%s", str1); // 输出字符串str1
scanf("%s", str1); // 输入字符串到str1(遇到空白字符停止输入)
These are some common methods for using character arrays, as well as many other operations and functions that can be used to manipulate character arrays.