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

C++ String Methods

Finding String Length

.length() and .size() are functionally identical and both return the exact number of characters currently stored in a std::string.size() exists for consistency with other STL containers, while .length() reads a bit more naturally for strings specifically, but you can use either interchangeably.

Example: Finding String Length

cpp
#include <iostream>
#include <string>

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

Checking if Empty

.empty() returns true if a string has zero characters and false otherwise, and it's generally preferred over checking str.length() == 0, since it reads clearly as a direct yes/no question and can be marginally more efficient for some string implementations.

Example: Checking if Empty

cpp
#include <iostream>
#include <string>

int main() {
	std::string s = "";
	std::cout << (s.empty() ? "empty" : "not empty") << std::endl;
	return 0;
}

Finding Substrings

.find(substring) searches the string for the first occurrence of a given substring and returns the index where it starts, or the special constant string::npos if no match exists anywhere in the string — always check the result against npos before using it, since a failed search doesn't throw an error, it just returns that sentinel value.

Example: Finding Substrings

cpp
#include <iostream>
#include <string>

int main() {
	std::string s = "Hello, world";
	std::cout << s.find("world") << std::endl;
	return 0;
}

Modifying Strings

.append() adds text to the end of a string, .insert(pos, text) injects text at a specific index shifting the rest of the string over, and .erase(pos, count) removes a given number of characters starting at a position — together these give you full control over building and editing strings piece by piece.

Example: Modifying Strings

cpp
#include <iostream>
#include <string>

int main() {
	std::string s = "Hello";
	s.append(", world");
	s.insert(0, ">> ");
	std::cout << s << std::endl;
	return 0;
}

Getting Substrings

.substr(start, length) extracts a copy of part of the string, starting at index start and taking up to length characters (or everything to the end if length is omitted) — the original string is left completely unchanged, since .substr() always returns a brand-new string rather than modifying in place.

Example: Getting Substrings

cpp
#include <iostream>
#include <string>

int main() {
	std::string s = "Hello, world";
	std::cout << s.substr(7, 5) << 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.