c++ string index access 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: 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 3: c++ first letter of string

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

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

Tags:

Java Example