C++ String Characters Accessing

Introduction

Individual characters of a string can be accessed through a subscript operator [] or via a member function .at(index).

The index starts at 0.

Example:

#include <iostream> 
#include <string> 

int main() // w ww  .ja v a  2 s  . c om
{ 
    std::string s = "Hello World."; 
    char c1 = s[0];        // 'H' 
    char c2 = s.at(0);     // 'H'; 

    char c3 = s[6];        // 'W' 
    char c4 = s.at(6);     // 'W'; 

    std::cout << "First character: " << c1 << ", sixth character: " << c3; 
} 



PreviousNext

Related