Home  >  Article  >  Backend Development  >  How Can I Check If a C String Contains a Substring?

How Can I Check If a C String Contains a Substring?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-23 18:52:11554browse

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:

  • str is the substring to search for.
  • pos is an optional starting position to begin the search from (default is 0).

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:

  • s1 is the string to search in.
  • s2 is the substring to search for.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn