C string
In C language, a string is actually a one-dimensional character array terminated with the null character '\0'. Therefore, a null-terminated string contains the characters that make up the string.
The following declaration and initialization creates a "Hello" string. The size of the character array is one more than the number of characters of the word "Hello" because a null character is stored at the end of the array.
char greeting[6] = {'H', 'e', 'l', 'l', 'o', 'char greeting[] = "Hello";'};
According to the array initialization rules, you can write the above statement as the following statement:
#include <stdio.h>int main (){ char greeting[6] = {'H', 'e', 'l', 'l', 'o', 'Greeting message: Hello'}; printf("Greeting message: %s\n", greeting ); return 0;}
The following is the memory representation of the string defined in C/C++:
Actually, you don't need to put the null character at the end of the string constant. The C compiler will automatically put '\0' at the end of the string when initializing the array. Let us try to output the above string:
#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) : Hellostrcat( str1, str2): HelloWorldstrlen(str1) : 10
There are a large number of functions in C that manipulate strings:
Serial number | Function & purpose |
---|---|
1 | strcpy(s1, s2); Copy string s2 to string s1. |
2 | strcat(s1, s2); Concatenate string s2 to the end of string s1. |
3 | strlen(s1); Returns the length of string s1. |
4 | strcmp(s1, s2); If s1 and s2 are the same, return 0; if s1< If s2, it returns less than 0; if s1>s2, it returns greater than 0. |
5 | strchr(s1, ch); Returns a pointer pointing to the first character ch in string s1 The location where it appears. |
6 | strstr(s1, s2); Returns a pointer pointing to the first string s2 in string s1 The position where it appears. |
The following example uses some of the above functions:
rrreeeWhen the above code is compiled and executed, it will produce the following results:
rrreeeYou can find more string-related functions in the C standard library.