string indexing in c++ code example

Example 1: c++ string element access

// 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 2: 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;
}

Example 3: how to access the element of string in c++

string myString = "Hello";
cout << myString[0];
// Outputs H

Tags:

Java Example