Home C++ Strings Functions starts_with() C++ std::string starts_with() Function Definition In C++, std::string::starts_with() tells you whether the string begins with a given prefix (C++20).
Include <string>.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax Pass a prefix string or character.
bool ok = s.starts_with("https");
bool bang = s.starts_with('!'); Call What it does s.starts_with(prefix)True if s begins with prefix. s.starts_with(ch)True if the first character is ch.
Pre-C++20: compare s.rfind(prefix, 0) == 0 or compare a substr.
Library declarations bool starts_with(string_view sv) const noexcept; // C++20
bool starts_with(char ch) const noexcept;
bool starts_with(const char* s) const; Parameters Parameter Description prefix Expected starting text or character.
Return Value Return Value Description boolTrue when the prefix matches.
C++ Examples 1. URL scheme 2. First char 3. No match Example 1 — Basic starts_with Check https prefix.
#include <iostream>
#include <string>
int main() {
std::string url = "https://example.com";
std::cout << std::boolalpha << url.starts_with("https") << '\\n';
return 0;
} How It Works The string begins with https. starts_with returns true. Useful for quick protocol checks. Example 2 — Starts With Char Check a leading slash.
#include <iostream>
#include <string>
int main() {
std::string path = "/tmp";
std::cout << std::boolalpha << path.starts_with('/') << '\\n';
return 0;
} How It Works First character is '/'. Character overload returns true. False would mean a relative path in this example. Example 3 — Prefix Missing Wrong prefix returns false.
#include <iostream>
#include <string>
int main() {
std::string s = "CodeToFun";
std::cout << std::boolalpha << s.starts_with("Fun") << '\\n';
return 0;
} How It Works "Fun" is a suffix, not a prefix.starts_with is false. Use ends_with for suffix checks. Frequently Asked Questions What does starts_with do? Returns true if the string begins with the given prefix.
Empty prefix? Typically matches every string.
Pre-C++20 alternative? Compare s.compare(0, prefix.size(), prefix) == 0 or use rfind(prefix, 0) == 0.
Next: substr() Keep going through the string functions. Return a new string that is a slice of this string.
substr() tutorial → CODETOFUN NEWS
Stay Ahead in Tech Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
7 people found this page helpful
Helpful Share Copy link Suggestion