is substring c++ code example

Example 1: c++ check substring

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

Example 2: how to check string contains char in c++

std::string s = "Hello";
if (s.find('e') != std::string::npos)
    cout << "Found";
else
    cout << "Not Found";

Example 3: c++ check if string contains substring

string str ("There are two needles in this haystack.");
string str2 ("needle");

if (str.find(str2) != string::npos) {
//.. found.
}

Example 4: splice string in c++

string str1 = "Apples are red";
string str2 = str1.substr(11, 3); // "red"
string str3 = str1.substr(0, 6); // "Apples"

Example 5: create copy of range of string c++

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

Tags:

Cpp Example