Home >Backend Development >C++ >How Can I Check if a String Contains a Substring in C ?

How Can I Check if a String Contains a Substring in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-24 08:29:09693browse

How Can I Check if a String Contains a Substring in C  ?

Determining the Presence of a Substring in a String in C

In C , a common task programmers encounter is checking if a string contains another string. To accomplish this, several methods are available.

One efficient method is to utilize the std::string::find function. This function returns the position of the first occurrence of the specified substring within the string. If the substring is absent, std::string::npos is returned, a special value indicating that the substring is not present.

To check if a string contains a substring, you can employ the following steps:

  1. Declare two string variables, s1 and s2.
  2. Assign the string you want to search to s1 and the substring you want to find to s2.
  3. Use the find function to determine the position of s2 within s1.
  4. Compare the returned position with std::string::npos. If the position is not std::string::npos, it means the substring was found.

Here's an example:

if (s1.find(s2) != std::string::npos) {
    std::cout << "found!" << '\n';
}

In this code, if s2 is a substring of s1, "found!" will be printed. Remember, both s1 and s2 must be of type std::string.

The above is the detailed content of How Can I Check if a String Contains a Substring in C ?. 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