May 11, 2021 C
In the C language, a string is actually an array of one-dimensional characters terminated with the null character ''. Therefore, a string that ends with null contains the characters that make up the string.
The following declaration and initialization create a "Hello" string. Because empty characters are stored at the end of the array, the character array is one more size than the number of characters in the word "Hello".
char greeting[6] = {'H', 'e', 'l', 'l', 'o', ''};
Depending on the array initialization rules, you can write the above statement as follows:
char greeting[] = "Hello";
Here is the memory representing the string defined in C/C?
In fact, you don't need to put the null character at the end of the string constant. T he C compiler automatically places '' at the end of the string when the array is initialized. Let's try to output the string above:
#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', ''};
printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following results:
Greeting message: Hello
C has a large number of functions that manipulate strings:
Serial number | Function & purpose |
---|---|
1 |
strcpy(s1, s2);
Copy the string S2 to the string S1. |
2 |
strcat(s1, s2);
Connect the string S2 to the end of the string S1. |
3 |
strlen(s1);
Returns the length of the string S1. |
4 |
strcmp(s1, s2);
如果 s1 和 s2 是相同的,则返回 0;如果 s1<s2 则返回小于 0;如果 s1>s2 则返回大于 0。 |
5 |
strchr(s1, ch);
Returns a pointer, pointing to the first appearance of the character chi in the string S1. |
6 |
strstr(s1, s2);
Returns a pointer to a position where the character string S2 in the string S1 is returned. |
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.