C++ Basics: Match Text Prefixes and Suffixes
Use starts_with and ends_with for literal text checks without manual substring arithmetic.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need 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 string-view-prefix-suffix-tests-demo.cpp:
#include <array>
#include <iostream>
#include <string_view>
int main()
{
constexpr std::array<std::string_view, 4> names{
"report.csv", "report.CSV", "old-report.csv", "report"
};
std::cout << std::boolalpha;
for (auto name : names) {
std::cout << name << ": "
<< (name.starts_with("report") && name.ends_with(".csv"))
<< '\n';
}
std::cout << "empty prefix: " << names[0].starts_with("") << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic string-view-prefix-suffix-tests-demo.cpp -o string-view-prefix-suffix-tests-demo &&
./string-view-prefix-suffix-tests-demoObserved output:
report.csv: true
report.CSV: false
old-report.csv: false
report: false
empty prefix: trueRead the result
Only report.csv satisfies both checks. Matching is case-sensitive: .CSV differs from .csv. An empty prefix matches any string, including an empty one.
Apply it carefully
These are literal character-sequence tests, not glob patterns, regular expressions, Unicode case folding, or filesystem validation. A filename suffix does not prove the contents have that format. The views here refer to string literals, which remain alive for the entire program.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- string-view-prefix-suffix-tests-demo.cpp string-view-prefix-suffix-tests-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.