Loading lessons...
String Length
How long is a string? Ask .length() or .size() - they are the same method under two names.
length and size
cpp
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << txt.length() << endl; // 26
cout << txt.size() << endl; // 26
Both return the number of characters. Use whichever reads better to you; size() matches the containers you will meet later.
Whitespace counts
cpp
string spaced = "a b"; // 3 characters
string blank = " "; // 1 character
Spaces, tabs, and punctuation are characters too. Every character in the string counts toward the total.
Empty strings
cpp
string empty;
cout << empty.length() << endl; // 0
A string with no characters has length
- Checking for
length() == 0is a handy way to know the user typed nothing.
TL;DR
.length()and.size()return the character count.- Whitespace and punctuation count as characters.
- An empty string has length 0.