如何在字符串向量中引用字符串的特定字符
How to refer to specific character of a string in a string vector?
我需要通过向量数组中每个字符串的字符进行双循环,并且我正在卡住语法如何调用每个元素的每个字符。
向量[] operator
将返回std::string&
,然后使用std::string
的[] operator
来获得字符(如char&
)。
std::vector<std::string> vec{"hello","world"};
std::cout<<vec[0][3];
正如@RyanP所评论的,方法std::vector::at
和std::string::at
将执行边界检查,如果您试图解引用大于向量/字符串大小的索引,则会抛出异常。
try{
std::cout<<vec.at(0).at(3);
}
catch (std::exception& e){
//handle
}
当你需要迭代vector中的string时,即多次使用它,创建一个(const)引用:
std::vector<std::string> vec { "abc", "efg" };
for( size_t i = 0; i < vec.size(); ++i ) {
const auto &str = vec[i];
for( size_t j = 0; j < str.length(); ++j )
std::cout << str[j];
}
否则您将不得不多次写入vec[i][j]
,这太啰嗦了
这里展示了不同的方法
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> v = { "Hello", "World" };
for ( const auto &s : v )
{
for ( auto c : s ) std::cout << c;
std::cout << ' ';
}
std::cout << std::endl;
for ( auto i = v.size(); i != 0; )
{
for ( auto j = v[--i].size(); j != 0; ) std::cout << v[i][--j];
std::cout << ' ';
}
std::cout << std::endl;
for ( auto it1 = v.begin(); it1 != v.end(); ++it1 )
{
for ( auto it2 = it1->rbegin(); it2 != it1->rend(); ++it2 ) std::cout << *it2;
std::cout << ' ';
}
std::cout << std::endl;
}
程序输出为
Hello World
dlroW olleH
olleH dlroW
您可以以各种方式组合这些方法。
如果你想使用基于范围的for语句改变字符串中的一个字符,那么你必须按照以下方式编写循环
for ( auto &s : v )
{
for ( auto &c : s ) /* assign something to c */;
}
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么没有访问所有字符串字符?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何将字符串字符与结构数组进行比较?
- 将单个字符串/字符输入串行监视器
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++ C 样式字符串/字符数组的大小 - 优化
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 在另一个字符串中逐个复制字符串字符
- 将字符串字符映射到矢量
- MBED RTOS将Float转换为字符串/字符阵列
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 如何比较C++中的单个字符串字符?
- 内部字符串/字符如何在 int 和 float 中存储
- 将十六进制转换为可打印的字符串/字符
- wcscpy_s后读取字符串字符时出错
- 检查字符串字符和长度