C++ Basics: Find the First of Several Delimiters
Use std::find_first_of to locate the earliest character belonging to a delimiter set, rather than searching for a multi-character substring.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as find-first-of-delimiter-set-demo.cpp:
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string text = "alpha,beta;gamma";
std::string delimiters = ";,";
auto found = std::find_first_of(text.begin(), text.end(),
delimiters.begin(), delimiters.end());
if (found != text.end()) {
std::cout << "index: " << found - text.begin() << '\n';
std::cout << "delimiter: " << *found << '\n';
}
std::string none;
std::cout << "empty set found: "
<< (std::find_first_of(text.begin(), text.end(), none.begin(), none.end())
!= text.end()) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic find-first-of-delimiter-set-demo.cpp -o find-first-of-delimiter-set-demo &&
./find-first-of-delimiter-set-demoObserved output:
index: 5
delimiter: ,
empty set found: 0Read the result
The comma at index 5 wins even though the delimiter list places semicolon first. An empty delimiter set cannot match a character.
Apply it carefully
Always test for end before dereferencing the result. The delimiter range is a set of alternatives, not a pattern that must appear contiguously; search handles a multi-element pattern. With std::string this example compares char values, so it is suitable for these ASCII delimiters, not general Unicode character segmentation. This is also not a CSV parser: quoted commas require a format-aware parser.
The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- find-first-of-delimiter-set-demo.cpp find-first-of-delimiter-set-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.