Saturday, June 27, 2020

Ways of accessing a String element

In this section I am going to share a number of ways to access the elements in a String.

Method 1. With "loop" and "indexing" like an array

std::string name  = "Ghost";
for(int i = 0; name[i] != '\0'; i++){
    std::cout<<name[i];
}

//output: Ghost

Method 2. With "at(i)"

std::string name = "Ghost";
std::cout<<name.at(0);

//output: G

Method 2. With "front" and "back"

std::string name = "Ghost";
std::cout<<name.front()<<"\n";
std::cout<<name.back();

//output: G
               t
front and back are only allowed in non empty strings. If the string is empty it will give an error.


No comments:

Post a Comment

horizontal ads