C++ String Length
Sometimes you need to know how many characters are in a string, for example to check if a password is long enough. C++ makes this easy with the length() and size() functions.
Measuring a string
Every string knows its own length. You can ask for it by calling .length() or .size() on the string. Both return the same number: the count of characters in the string, including spaces.
Finding the length
#include <iostream>
#include <string>
using namespace std;
int main() {
string city = "London";
cout << "Length: " << city.length() << "\n"; // 6
cout << "Size: " << city.size() << "\n"; // 6
return 0;
}The two functions are interchangeable, so use whichever name reads more naturally to you. Many programmers prefer length() for text because it clearly describes what it measures. Remember that spaces and punctuation count as characters too.
Length includes spaces
#include <iostream>
#include <string>
using namespace std;
int main() {
string phrase = "Hi there";
cout << phrase.length() << "\n"; // 8, the space counts
string empty = "";
cout << empty.length() << "\n"; // 0
return 0;
}- length() and size() give the same result
- The count includes spaces and punctuation
- An empty string has a length of 0
- Use the length to check limits, like a minimum password size
Length examples
Note: length() returns an unsigned type, so avoid subtracting past zero in comparisons. If you write s.length() - 5 when the string is shorter than 5 characters, the result wraps around to a huge number instead of going negative.