c++ string indexOF code example

Example 1: index string c++

#include <string>
#include <iostream>

int main(){
  //index string by using brackets []
  std::string string = "Hello, World!";
  //assign variable to string index
  char stringindex = string[2];
  
}

Example 2: c++ string contains

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

Example 3: indexing strings in c++

// string::operator[]
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  for (int i=0; i<str.length(); ++i)
  {
    std::cout << str[i];
  }
  return 0;
}

Example 4: string .find in c++

std::string t = "Banana Republic";
std::string s = "nana";

std::string::size_type i = t.find(s);

if (i != std::string::npos)
   t.erase(i, s.length());

Example 5: find in string c++

size_t find (const string& str, size_t pos = 0) const;

Tags:

Cpp Example