get character from string c++ code example

Example 1: find character in string c++

auto char_to_find = 'a'
if (str.find(char_to_find) != std::string::npos) {
    // character found
}

Example 2: 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 3: c++ get character from string

#include <iostream>
#include <string>

int main() {
    std::string myStr = "test string";

    for (int i = 0; i < myStr.length(); ++i) {
        std::cout << myStr.at(i) << std::endl;
    }

    return 0;
}

Example 4: 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 5: working with char and string c++

String and Char

Tags:

Cpp Example