C++ String Length
In this page:
The length() Method
The length() member function returns the number of characters currently stored in a std::string, not including any hidden terminator, since std::string manages its own size internally.
Example: The length() Method
#include <iostream>
#include <string>
int main() {
std::string name = "Alex";
std::cout << name.length() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The size() Method
size() returns exactly the same value as length() -- both exist because std::string implements the same interface as other STL containers, where size() is the conventional name.
Example: The size() Method
#include <iostream>
#include <string>
int main() {
std::string name = "Alex";
std::cout << name.size() << std::endl; // same value as length()
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Checking for an Empty String
The empty() method returns true if a string has zero characters, which is a clearer and slightly more efficient way to check emptiness than comparing length() to 0.
Example: Checking for an Empty String
#include <iostream>
#include <string>
int main() {
std::string name = "";
if (name.empty()) {
std::cout << "Empty" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using Length in a Loop
A string's length() is commonly used as the upper bound of a loop that visits each character by index, ensuring the loop never reads past the end of the string.
Example: Using Length in a Loop
#include <iostream>
#include <string>
int main() {
std::string word = "Hello";
for (int i = 0; i < word.length(); i++) {
std::cout << word[i] << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Length vs Capacity
A string's length() reflects how many characters it actually holds, while its internal capacity() -- the memory currently reserved -- can be larger, since std::string over-allocates to make future growth faster.
Example: Length vs Capacity
#include <iostream>
#include <string>
int main() {
std::string s = "Hi";
std::cout << "length=" << s.length() << " capacity=" << s.capacity() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- C++ Arrays Introduction
- C++ Looping Through Arrays
- C++ Omitting Array Size
- C++ Array Size
- C++ Multi-dimensional Arrays
- C++ Arrays & Functions
- C++ Strings (C-style)
- C++ std::string
- C++ String Concatenation
- C++ Converting Strings and Numbers
- C++ String Length
- C++ Accessing String Characters
- C++ using namespace std
- C++ String Methods
- C++ Array of Strings