The short answer
A string holds characters: letters, digits, spaces, punctuation and other symbols. In C, a string also has a null character at the end, which marks where the text stops. In C++, std::string keeps its characters and tracks how many there are.
A C string is a char array with a null ending
A C string is stored as an array of char. The text comes first, and a null character ('\0') follows it. The null is not visible text, but functions use it to find the end.
#include <stdio.h>
#include <string.h>
int main(void) {
char word[] = "Cat";
printf("strlen: %zu\n", strlen(word));
printf("sizeof: %zu\n", sizeof(word));
return 0;
}
Output:
strlen: 3
sizeof: 4
The array holds these four values:
| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Value | 'C' |
'a' |
't' |
'\0' |
strlen counts the characters before the null, so it returns 3. sizeof counts every byte in the array, including the null, so it returns 4.
If you fill a char array by hand, leave room for the null. An array declared as char word[3] = {'C', 'a', 't'}; has no null, so functions such as strlen can read past the end of the array.
What a C++ std::string holds
A std::string holds characters and also records its size, so it does not depend on a null character to know its length.
#include <iostream>
#include <string>
int main() {
std::string word = "Cat";
std::cout << "size: " << word.size() << '\n';
std::cout << "text: " << word << '\n';
}
Output:
size: 3
text: Cat
size() counts the characters and does not include a terminating null. If you need a C-style pointer, c_str() returns one that ends in a null character.
A std::string can hold a null character inside its text, when you give its length explicitly, as in std::string text("a\0b", 3);. Many C functions stop at the first null, so this can cause surprises when the string is passed to C code.
Empty strings and spaces
- An empty
std::stringholds no characters, andsize()returns 0. - In C,
""holds only the null character.strlenreturns 0, andsizeofreturns 1. - A space is a character.
"Hello world"has 11 characters, counting the space.
Checking what a string contains
C has no string type, so the work of searching a char array is done by functions in the standard headers, as explained in Is there a string library in C? In C++, searching a string for a word is a separate task, covered in the guide to c string contains.
Common mistakes
- Forgetting the null character when you fill a
chararray yourself. - Mixing up strlen and sizeof.
strlengives the length of the text.sizeofgives the size of the array, which includes the null. - Expecting size() to count the null in a
std::string. It does not.
Summary
- A string holds characters, including spaces and symbols.
- In C, a string is a
chararray that ends in a null character. - In C++,
std::stringstores its characters and its size.