[英]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]
? 我怎样才能从
str[0]
获得“ t”?
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
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. 这里的
str
是std::string
对象的数组。 As you know you access elements of an array with operator[]
. 如您所知,您可以使用
operator[]
访问数组的元素。 So the first string in the array is accessed with str[0]
. 因此,使用
str[0]
访问数组中的第一个字符串。
std::string
offers operator[]
as well. std::string
提供了operator[]
。 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]
You get 't' instead of 's' because you are printing it like this cout<<example[1];
之所以得到't'而不是's',是因为您要像
cout<<example[1];
这样打印它cout<<example[1];
you sohuld do it like this: 您应该这样做:
cout<<example[0][2];
YOu need one more operator[]
call. 您还需要一个
operator[]
调用。 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[2]
使用数组的[]
并返回索引2处对数组元素的引用。如果要获取第一个数组元素的第二个字符,则需要
str[0][2]
^ ^
string |
character
Class std::string has its own overloaded operator []
that you used in the first your code snippet 类std :: string具有自己的重载
operator []
,您在代码段的第一个中使用了该operator []
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 如果您有一个
std::string
类型的对象数组,那么首先需要使用数组的内置下标operator []
来访问存储在数组中的所需对象,例如
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. 在这段代码中,
str[1]
返回存储在数组的第二个元素(索引为1)中的字符串。 Now you can apply the overloaded operator []
of the class std::string
as for example 现在,您可以应用
std::string
类的重载operator []
,例如
string str[4];
cout << str[1][1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.