gpt4 book ai didi

c++ - 迭代 std::string 并提取字符和整数

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:19 28 4
gpt4 key购买 nike

我希望遍历这样的字符串:

string mystr = "13n4w14n3w2s";

如果可能的话,我希望从该字符串中提取出某种 map ,但要保持找到它的顺序。

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.
}

Here is a link to a demo on ideone.

关于c++ - 迭代 std::string 并提取字符和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23548689/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com