如何从字符串向量中选择第 n 个位置?
How to select the nth position from a string vector?
比方说,如何从字符串向量中找到第二个位置?
下面是一个字符串向量示例:
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
中的位置。
因此,在您的情况下,在第一行获取字符串的第一char
是example[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()
来分析字符串。
相关文章:
- 如何使用默认参数等选择模板专业化
- 将值指定给向量(2D)的向量中的某个位置
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 使用Unreal C++获取VR耳机的世界位置/方向
- 如何选择在 csv 文件中输出的位置
- 如何从字符串向量中选择第 n 个位置?
- 如何选择文件保存到的位置?
- 在队列中选择备用位置
- 最佳的c++方式来随机选择设置位在位集中的位置
- MFC 打开文件位置并选择(突出显示)该文件
- 通过在每个位置从特定位置的单词池中选择单词,有效地生成所有序列
- 如何从字符串中一次选择两个字符?到达字符串的第 i 个位置
- 强制 cmake 选择依赖位置(如果存在多个)
- COM 代码库位置 - 如何选择要使用的版本
- Qt选择矩形位置
- EM_EXGETSEL与文本选择顺序无关.如何确定一段选定文本中的插入符号位置
- 当位置超出范围时,如何从数组中选择值
- 如何通过鼠标单击在QGraphicsView中选择位置并添加项目
- mfccfiledialog在用户最后运行时选择的位置打开
- OpenGL拾取选择错误的位置