Search⌘ K
AI Features

Other Common String Operations

Explore essential string operations in C++ including substring searching, lexicographic comparison, case conversion, and trimming. Understand how to use std::string methods like find, rfind, and the C++20 starts_with and ends_with. This lesson prepares you to handle common string manipulation tasks efficiently, improving your ability to solve string algorithm problems.

Knowing the basic string operations such as finding the length, traversal, indexing, concatenation, and slicing is an important start. A problem may ask whether two strings are equal, whether one string starts with another, whether a smaller string appears inside a larger one, or how to transform a string for case-insensitive processing. These additional operations will better prepare you for a wider range of string algorithms.

Searching within a string

Searching refers to locating a character or a substring within a larger string. The std::string class provides the find() member function, which returns the starting index of the first occurrence. If the substring is not found, find() returns the special constant std::string::npos.

C++ 17
#include <iostream>
#include <string>
int main() {
std::string s = "hello world";
std::cout << "string: \"" << s << "\"" << std::endl;
// Find the starting index of "world"
size_t pos = s.find("world");
if (pos != std::string::npos) {
std::cout << "\n\"world\" found at index: " << pos << std::endl;
} else {
std::cout << "\n\"world\" not found" << std::endl;
}
// Searching for a substring that does not exist
pos = s.find("xyz");
if (pos != std::string::npos) {
std::cout << "\n\"xyz\" found at index: " << pos << std::endl;
} else {
std::cout << "\n\"xyz\" not found" << std::endl;
}
return 0;
}

The find() method scans the string from left to right and returns the index of the first match. Always check the return value against std::string::npos before using the index.

Finding from the end and finding any of a set

C++ provides several additional search variants:

  • rfind(str) searches from right to left, returning the index of the last occurrence.

  • find_first_of(str) returns the index of the first character that matches any character in the given set.

  • find_last_of(str) returns the index of the last character that matches any character in the given set.

C++ 17
#include <iostream>
#include <string>
int main() {
std::string s = "hello world";
std::cout << "string: \"" << s << "\"" << std::endl;
// Find the last occurrence of 'l'
std::cout << "\nLast 'l' at index: " << s.rfind("l") << std::endl;
// Find the first vowel
size_t firstVowel = s.find_first_of("aeiouAEIOU");
std::cout << "\nFirst vowel at index: " << firstVowel << std::endl;
return 0;
}

Checking for existence without needing the

...