Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Strings

C Strings

In C, a string is actually a one-dimensional array of characters terminated by the null character \0. Thus, \0 is used to mark the end of a string.

The null character (Null character) is also called the terminator, abbreviated NUL; it is a control character with the value 0. \0 is an escape sequence that tells the compiler this is not the character 0 but the null character.

The declaration and initialization below creates a RUNOOB string. Because the null character \0 is stored at the end of the array, the size of the character array is greater than that of the word RUNOOB .



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[] = "RUNOOB";

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

In fact, you do not need to put the null character at the end of a string constant. When initializing an array, the C compiler automatically places \0 at the end of the string. Let's try printing the string above:

Example

#include

<

stdio.h

int

main

(

)

{

char

site

[

7

]

=

{

'

R

', '

U

', '

N

', '

O

', '

O

', '

B

', '\

0

'

}

;

printf

(

"

Runoob Tutorial: %s

\

n

"

,

site

)

;

return

0

;

}

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



Runoob Tutorial: RUNOOB

C has a large number of functions for manipulating strings:

No. Function & Purpose
1 strcpy(s1, s2);
Copies string s2 to string s1.
2 strcat(s1, s2);
Appends string s2 to the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are identical; if s1s2, returns a value greater than 0.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

The example below uses some of the functions above:

Example

#include

<

stdio.h

#include

<

string.h

int

main

(

)

{

char

str1

[

14

]

=

"

runoob

"

;

char

str2

[

14

]

=

"

google

"

;

char

str3

[

14

]

;

int

len

;

/*

Copy str1 to 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

)

;

/*

After concatenation, the total length of str1

*/

len

=

strlen

(

str1

)

;

printf

(

"

strlen(str1) : %d

\

n

"

,

len

)

;

return

0

;

}

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



strcpy( str3, str1) :  runoob

strcat( str1, str2):   runoobgoogle

strlen(str1) :  12

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