← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 11 of 15

C++ String Length

The length() and size() member functions both return the number of characters in a std::string, and empty() checks whether a string has zero characters, without needing manual counting.

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

cpp
#include <iostream>
#include <string>

int main() {
	std::string name = "Alex";
	std::cout << name.length() << std::endl;
	return 0;
}

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

cpp
#include <iostream>
#include <string>

int main() {
	std::string name = "Alex";
	std::cout << name.size() << std::endl; // same value as length()
	return 0;
}

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

cpp
#include <iostream>
#include <string>

int main() {
	std::string name = "";
	if (name.empty()) {
		std::cout << "Empty" << std::endl;
	}
	return 0;
}

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

cpp
#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;
}

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

cpp
#include <iostream>
#include <string>

int main() {
	std::string s = "Hi";
	std::cout << "length=" << s.length() << " capacity=" << s.capacity() << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.