Ph.nischkar
Ph.nischkar

Reputation: 41

C++ Reading from array of strings

Question: How do I extract a character from a string that is an array?

Explained: Normal strings

 string example=("Stack Over Flow");
 cout<<example[1];

The output will be:

 t

What I want is to extract a letter from an array of strings example:

string str[4];
str[0]="1st";
str[1]="2nd";
str[2]="3rd";
str[3]="4th";
cout<<str[2];

will print

3rd

how could i get the "t" from the str[0]?

Upvotes: 1

Views: 1304

Answers (5)

mheonyae
mheonyae

Reputation: 643

You get 't' instead of 's' because you are printing it like this cout<<example[1];

you sohuld do it like this:

cout<<example[0][2];

Upvotes: 0

rozina
rozina

Reputation: 4232

std::string str[4];
str[0]="1st";
str[1]="2nd";
str[2]="3rd";
str[3]="4th";

Here str is an array of std::string objects. As you know you access elements of an array with operator[]. So the first string in the array is accessed with str[0].

std::string offers operator[] as well. With it you can access characters of the string.

So lets take it step by step.

str - array
str[0] - std::string
str[0][0] - first character of the string str[0]

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

Class std::string has its own overloaded operator [] that you used in the first your code snippet

 string example=("Stack Over Flow");
 cout<<example[1];

If you have an array of objects of type std::string then at first you need to access the desired object stored in the array using the built-in subscript operator [] of arrays as for example

string str[4];
cout << str[1];

In this code snippet expression str[1] returns string stored in the second element (with index 1) of the array. Now you can apply the overloaded operator [] of the class std::string as for example

string str[4];
cout << str[1][1];

Upvotes: 0

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 8066

just by doing as follow:

str[0][2]; // third character of first string

Some more examples:

string str[4];
str[0]="1st";
str[1]="2nd";
str[2]="3rd";
str[3]="4th";
cout<<str[0][2]<<endl; // t
cout<<str[2][1]<<endl; // r
cout<<str[3][2]<<endl; // h

Upvotes: 6

NathanOliver
NathanOliver

Reputation: 180415

YOu need one more operator[] call. str[2] is using the [] of the array and returns a reference to the array element at index 2. If you want to get the second character of the first array element then you need

str[0][2]
    ^  ^
string |
       character

Upvotes: 0

Related Questions