Home > Article > Backend Development > How Can I Check If a C String Contains a Substring?
Finding a Substring in a C String
Given a string stored in a std::string variable, it is often necessary to determine if it contains a specific substring. C provides a straightforward method to perform this check using the std::string::find function.
The syntax of std::string::find is as follows:
std::string::size_type find(const std::string& str, int pos = 0) const;
where:
The function returns a std::string::size_type value, which represents the index of the first occurrence of the specified substring. If the substring is not found, it returns std::string::npos.
To check if a string contains a substring, you can use the following code:
if (s1.find(s2) != std::string::npos) { std::cout << "found!" << '\n'; }
where:
If s2 is found in s1, the std::string::npos check will fail, resulting in a "found!" message being printed. Note that the search is case-sensitive, meaning that s2 must exactly match the characters in s1.
The above is the detailed content of How Can I Check If a C String Contains a Substring?. For more information, please follow other related articles on the PHP Chinese website!