[英]C++ Reading from array of strings
問題:如何從數組字符串中提取字符?
解釋:普通字符串
string example=("Stack Over Flow");
cout<<example[1];
輸出將是:
t
我想要的是從字符串數組示例中提取一個字母:
string str[4];
str[0]="1st";
str[1]="2nd";
str[2]="3rd";
str[3]="4th";
cout<<str[2];
將打印
3rd
我怎樣才能從str[0]
獲得“ t”?
只需執行以下操作:
str[0][2]; // third character of first string
其他示例:
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";
這里的str
是std::string
對象的數組。 如您所知,您可以使用operator[]
訪問數組的元素。 因此,使用str[0]
訪問數組中的第一個字符串。
std::string
提供了operator[]
。 使用它可以訪問字符串的字符。
因此,讓我們逐步進行。
str - array
str[0] - std::string
str[0][0] - first character of the string str[0]
之所以得到't'而不是's',是因為您要像cout<<example[1];
這樣打印它cout<<example[1];
您應該這樣做:
cout<<example[0][2];
您還需要一個operator[]
調用。 str[2]
使用數組的[]
並返回索引2處對數組元素的引用。如果要獲取第一個數組元素的第二個字符,則需要
str[0][2]
^ ^
string |
character
類std :: string具有自己的重載operator []
,您在代碼段的第一個中使用了該operator []
string example=("Stack Over Flow");
cout<<example[1];
如果您有一個std::string
類型的對象數組,那么首先需要使用數組的內置下標operator []
來訪問存儲在數組中的所需對象,例如
string str[4];
cout << str[1];
在這段代碼中, str[1]
返回存儲在數組的第二個元素(索引為1)中的字符串。 現在,您可以應用std::string
類的重載operator []
,例如
string str[4];
cout << str[1][1];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.