C String

In the C language, strings actually use the null character\0The trailing one-dimensional character array. Therefore,\0is used to mark the end of a string.

Null character) also known as the terminator, abbreviatedNUL, is a numeric value of0control character,\0is an escape character, meaning to tell the compiler that this is not a character0, but rather a null character.

The following declaration and initialization creates aEXAMPLEstring. Since the null character is stored at the end of the array,\0, so the size of the character array is one greater than the word'sEXAMPLEcharacter count.

char site[7] = {'R', 'U', 'N', 'O', 'O', 'B', '\0'};

according to the array initialization rules, you can write the above statement as the following:

char site[] = "EXAMPLE";

The following is the memory representation of strings defined in C/C++:

C/C++ 中的字符串表示

Actually, you don't need to putnullThe character is placed at the end of the string constant. The C compiler will, when initializing the array, automatically\0at the end of the string. Let's try outputting the above string:

Example

#include <stdio.h> int main () { char site[7] = {'R', 'U', 'N', 'O', 'O', 'B', '\0'}; printf("Rookie Tutorial: %s\n", site ); return 0; }

When the above code is compiled and executed, it produces the following results:

Example: EXAMPLE

C has a large number of functions for manipulating strings:

Serial NumberFunction & Purpose
1strcpy(s1, s2);
Copy string s2 to string s1.
2strcat(s1, s2);
Concatenates string s2 to the end of string s1.
3strlen(s1);
Return the length of string s1.
4strcmp(s1, s2);
If s1 and s2 are the same, returns 0; if s1<s2, returns a value less than 0; if s1>s2, returns a value greater than 0.
5strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

The following example uses some of the above functions:

Example

#include <stdio.h> #include <string.h> int main () { char str1[14] = "example"; char str2[14] = "google"; char str3[14]; int len ; /*Copy str1 to str3*/ strcpy(str3, str1); printf("strcpy( str3, str1) : %s\n", str3 ); /*Connect str1 and str2*/ strcat( str1, str2); printf("strcat( str1, str2): %s\n", str1 ); /*After concatenation, the total length of 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) :  example
strcat( str1, str2):   examplegoogle
strlen(str1) :  12

You can find more string-related functions in the C standard library.

other extensions