如何在字符串向量中引用字符串的特定字符

How to refer to specific character of a string in a string vector?

本文关键字:字符串 字符 引用 向量      更新时间:2023-10-16

我需要通过向量数组中每个字符串的字符进行双循环,并且我正在卡住语法如何调用每个元素的每个字符。

向量[] operator将返回std::string&,然后使用std::string[] operator来获得字符(如char&)。

std::vector<std::string> vec{"hello","world"};
std::cout<<vec[0][3];

正如@RyanP所评论的,方法std::vector::atstd::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 */;
    }