In C, strings are actually one-dimensional arrays of characters terminated by a null character \0
. Therefore, \0
is used to mark the end of the string.
Null character (Null character), also known as the end-of-string character, abbreviated as NUL
, is a control character with a value of 0
. \0
is an escape character, meaning it tells the compiler that this is not the character 0
, but rather a null character.
The following declaration and initialization create a string tutorialpro. Since a null character \0
is stored at the end of the array, the size of the character array is one more than the number of characters in the word tutorialpro.
char site[7] = {'R', 'U', 'N', 'O', 'O', 'B', '\0'};
According to the rules of array initialization, you can write the above statement as:
char site[] = "tutorialpro";
The following is the memory representation of strings defined in C/C++:
Actually, you do not need to place the null
character at the end of a string constant. The C compiler automatically places the \0
at the end of the string when it initializes the array. Let's try to print the above string:
Example
#include <stdio.h>
int main ()
{
char site[7] = {'R', 'U', 'N', 'O', 'O', 'B', '\0'};
printf("tutorialpro.org: %s\n", site );
return 0;
}
When the above code is compiled and executed, it produces the following result:
tutorialpro.org: tutorialpro
There are a large number of string handling functions in C:
No. | Function & Purpose |
---|---|
1 | strcpy(s1, s2); <br>Copies string s2 into string s1. |
2 | strcat(s1, s2); <br>Concatenates string s2 onto the end of string s1. |
3 | strlen(s1); <br>Returns the length of string s1. |
4 | strcmp(s1, s2); <br>Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. |
5 | strchr(s1, ch); <br>Returns a pointer to the first occurrence of character ch in string s1. |
6 | strstr(s1, s2); <br>Returns a pointer to the first occurrence of string s2 in string s1. |
The following example uses some of these functions:
Example
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[14] = "tutorialpro";
char str2[14] = "google";
char str3[14];
int len ;
/* Copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* Concatenate str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* Total length of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
When the above code is compiled and executed, it produces the following result:
strcpy( str3, str1) : tutorialpro
strcat( str1, str2): tutorialprogoogle
strlen(str1) : 12
You can find more string-related functions in the C standard library.