As noted already, a “string” is not the same thing in C and C++, and you appear to be studying
C, not C++.
In C, a string is
an array of characters.
char s[13] = "Hello world!";
The number of characters
used in the string varies: the string ends when the character value is zero. We call this zero-value character “the null terminator” or “the null character”. We could rewrite the above declaration using strict array syntax:
char s[13] = { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0 };
In other words, c-strings are special because they have a built-in language literal syntax: stuff in double-quotes. But they are still just an array.
Be careful of the difference between
mutable and
const arrays. All string literals are const. Hence, the following are acceptable:
1 2
|
const char* s1 = "Hello";
char s2[] = "Hello";
|
The first (
s1) is a pointer to the const array "Hello".
You cannot modify it.
s1 and "Hello" are the same thing.
The second (
s2) is a mutable array (of six characters) that is initialized (copied) from the const array "Hello".
You can change any element of the array as you wish.
s2 is a different array from "Hello", located at different places in memory.
they just have the same element-wise values.
As usual with arrays, you must make sure that the array is large enough to hold all the characters you intend to use. And you can use the plethora of string handling functions in <string.h> to manipulate the contents of the array.
1 2 3 4 5 6 7
|
char s[50];
strcpy( s, "Hello" );
strcat( s, " " );
strcat( s, "World!" );
s[6] = tolower( s[6] );
printf( "%s\n", s );
|
Hope this helps.