繁体   English   中英

遍历std :: string并提取char和ints

[英]Iterate over a std::string and pull out chars and ints

我正在寻找一个像这样的字符串:

string mystr = "13n4w14n3w2s";

我想要提取的是一种尽可能从该字符串中提取的地图,但要保持其找到的顺序。

13 n
4 w
14 n
3 w
2 s

为此,我将在另一个时间点进行迭代。 现在,我已经看到了从“ 13a”之类的简单字符串中提取值的示例

string str = "13a";
int num;
char dir;

str >> num >> dir;

我该如何做类似于顶部的较长字符串的操作?

您可以使用std::istringstream并循环并像这样从流中读取:

std::string mystr = "13n4w14n3w2s";
std::istringstream iss{mystr};
std::vector<std::pair<int, char>> mappings; // To store the int-char pairs.
int num;
char dir;
while (iss >> num >> dir) {
    std::cout << num << std::endl;   // Next int from the stream.
    std::cout << dir << std::endl;   // Next char from the stream.
    mappings.emplace_back(num, dir); // Store the pair.
}

这是有关ideone演示的链接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM