Loading lessons...
String Length
String Length
How long is a string? Ask .length() or .size() - they are the same method under two names.
length and size
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
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
string empty;
cout << empty.length() << endl; // 0
A string with no characters has length 0. Checking for length() == 0 is 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.