gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
how to check if std::string starts with concrete character using std library
- User
how to check if std::string starts with concrete character using std library
- Assistant
In C++20 and later, the
std::stringclass has a member functionstarts_withthat can be used directly to check if a string starts with a specific character (or substring).Here is how you can check if a
std::stringstarts with a specific character using the standard library in C++20:#include <iostream> #include <string> int main() { std::string s = "hello"; if (s.starts_with('h')) { std::cout << "String starts with 'h'\n"; } else { std::cout << "String does not start with 'h'\n"; } return 0; }Explanation:
starts_withaccepts either a single character, astd::string_view, or a C-style string.- The call
s.starts_with('h')checks if the first character of the stringsis'h'.
For pre-C++20 code (before existed),