C string
In the C language, strings are actually using thenull character '\ 0' one-dimensional array of characters terminated.Therefore, a null-terminated string that contains the characters of the string.
The following statements create and initialize a "Hello" string. Since the end of the array to store the null character, so the size of the array of characters than the word "Hello" is more than a number of characters.
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Based array initialization rules, you can write the above statement the following statement:
char greeting[] = "Hello";
The following is a string of C / C ++ defined in memory, he said:
In fact, you do not need thenullcharacter at the end of the string constant. When the C compiler array initialization, automatically '\ 0' at the end of the string. Let's try the above output string:
#include <stdio.h> int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message: %s\n", greeting ); return 0; }
When the above code is compiled and executed, it produces the following results:
Greeting message: Hello
There are a large number of C functions to manipulate strings:
序号 | 函数 & 目的 |
---|---|
1 | strcpy(s1, s2); 复制字符串 s2 到字符串 s1。 |
2 | strcat(s1, s2); 连接字符串 s2 到字符串 s1 的末尾。 |
3 | strlen(s1); 返回字符串 s1 的长度。 |
4 | strcmp(s1, s2); 如果 s1 和 s2 是相同的,则返回 0;如果 s1<s2 则返回小于 0;如果 s1>s2 则返回大于 0。 |
5 | strchr(s1, ch); 返回一个指针,指向字符串 s1 中字符 ch 的第一次出现的位置。 |
6 | strstr(s1, s2); 返回一个指针,指向字符串 s1 中字符串 s2 的第一次出现的位置。 |
The following example uses some of the above functions:
#include <stdio.h> #include <string.h> int main () { char str1[12] = "Hello"; char str2[12] = "World"; char str3[12]; int len ; /* 复制 str1 到 str3 */ strcpy(str3, str1); printf("strcpy( str3, str1) : %s\n", str3 ); /* 连接 str1 和 str2 */ strcat( str1, str2); printf("strcat( str1, str2): %s\n", str1 ); /* 连接后,str1 的总长度 */ len = strlen(str1); printf("strlen(str1) : %d\n", len ); return 0; }
When the above code is compiled and executed, it produces the following results:
strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10
You can find more string-related functions in the C standard library.