[英]Iterate through the chars in a string array?
在C ++中,我有一個字符串數組,說:
string lines[3]
lines[0] = 'abcdefg'
lines[1] = 'hijklmn'
lines[2] = 'opqrstu'
有沒有辦法遍歷每個索引內的字符以及遍歷索引? 像lines[i[j]]
?
如果您具有C ++ 11,則可以將range用於循環和自動:
// Example program
#include <iostream>
#include <string>
int main()
{
std::string lines[3];
lines[0]="abcdefg";
lines[1]="hijklm";
// for( auto line: lines)//using range for loop and auto here
for(int i=0; i<3; ++i)
{
std::string::iterator it= lines[i].begin();
//for ( auto &c : line[i]) //using range for loop and auto here
for(; it!= lines[i].end(); ++it)
{
std::cout<<*it;
}
std::cout<<"\n";
}
}
O / P
abcdefg
希克爾姆
試試這個代碼:
std::string lines[3];
lines[0] = "abcdefg";
lines[1] = "hijklmn";
lines[2] = "opqrstu";
for (int i=0; i < lines.length(); ++i) {
for (int j=0; j < lines[i].length(); ++j) {
std::cout << lines[i][j];
}
}
是。
#include <iostream>
#include <string>
int main() {
std::string arr[3];
arr[0] = "abcdefg";
arr[1] = "defghij";
arr[2] = "ghijklm";
for(size_t i = 0; i < 3; ++i) {
for (auto it : arr[i]) {
std::cout << it;
}
std::cout << '\n';
}
return 0;
}
使用雙循環。 對於每一行,遍歷每個字符。 完全不允許這樣使用雙索引: arr[i,j]
或arr[i[j]]
; 它必須是arr[i][j]
。
但是,如果您使用的是std::string
, str.length()
需要迭代str.length()
或僅for (auto it : str)
,其中str = THE TYPE OF std::string
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.