如何从字符串向量中选择第 n 个位置?

How to select the nth position from a string vector?

本文关键字:位置 选择 字符串 向量      更新时间:2023-10-16

比方说,如何从字符串向量中找到第二个位置?

下面是一个字符串向量示例:

1 2 3 4 Hi
7 8 9 0 Bye
2 2 5 6 World

如果我使用 example.at(2) ,它会给我整行2 2 5 6 World

我只想从第一行获得2,而不是获得整行2 2 5 6 World.我该怎么做?

example.at(2) 的返回值是向量中的第 3 项,在本例中为 std::string

要访问字符串中的特定字符,可以使用operator[] .因此,要从第一行中选择 2,您只需执行以下操作:

example.at(0)[2];

所以你实际拥有的是string vector,其中string代表另一个维度,所以你有一个包含行和列的表,类似于 2D 数组,在其他方面要访问单个单元格,您需要 2 个索引,一个索引用于vector中的位置,另一个用于string中的位置。

因此,在您的情况下,在第一行获取字符串的第一charexample[0][0]的,要获得您正在寻找的字符串,您需要编写example.at(0)[2];

这应该有效:

#include <iostream>
#include <string>
#include <vector>
int main() {
  std::vector<std::string> strings;
  strings.push_back("1234Hi");
  strings.push_back("7890Bye");
  std::cout << strings.at(0)[1] << std::endl; // prints 2
  std::cout << strings.at(1)[1] << std::endl; // prints 8
}

它有点像二维数组:你推送到向量的每个字符串都类似于第一维,然后字符串的每个字符都类似于第二维。

但如上所述,可能有更好的方法来做到这一点,这取决于你到底想做什么。

其他答案向您展示如何访问字符串中的单个数字,但它们假设数字的长度始终为 1 位。 如果需要支持多位数数字,请改用 std::istringstream()std::stoi() 来分析字符串。