循环访问字符串数组中的字符
Iterate through the chars in a string array?
在C++中,我有一个字符串数组,比如:
string lines[3]
lines[0] = 'abcdefg'
lines[1] = 'hijklmn'
lines[2] = 'opqrstu'
有没有办法遍历每个索引中的字符以及遍历索引? 像lines[i[j]]
?
试试这段代码:
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];
}
}
如果您有 C++11,则可以使用 range for 循环和自动:
// 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
阿克德夫
希克勒姆
是的。
#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()
或仅使用for (auto it : str)
,其中str = THE TYPE OF std::string
。
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?