繁体   English   中英

从没有空格的字符串中提取整数

[英]Extracting integers from a string which has no space

所以我目前正在尝试从字符串中提取整数。 这是我到目前为止所做的

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main() {
    string s="VA 12 RC13 PO 44";
    stringstream iss;
    iss << s;
    string temp;
    vector<int> a1;
    int j;
    while (!iss.eof()) {
           iss >> temp;
           if (stringstream(temp)>>j) {
               a1.push_back(j);
           }
           temp="";
   }
}

现在,这可以正常工作,但是如果我将字符串更改为类似 s="VA12RC13PO44" 的字符串,也就是没有空格,则此代码不起作用。 有谁知道如何解决这个问题? 谢谢

确实有很多很多可能的解决方案。 这取决于你有多先进。 就我个人而言,我总是会为此类任务使用std::regex方法,但这可能太复杂了。

一个简单的手工解决方案可能是这样的:

#include <iostream>
#include <string>
#include <vector>
#include <cctype>

int main() {
    std::string s = "VA 12 RC13 PO 44";
    std::vector<int> a;

    // We want to iterate over all characters in the string
    for (size_t i = 0; i < s.size();) {

        // Basically, we want to continue with the next character in the next loop run
        size_t increments{1};

        // If the current character is a digit, then we convert this and the following characters to an int
        if (std::isdigit(s[i])) {
            // The stoi function will inform us, how many characters ahve been converted.
            a.emplace_back(std::stoi(s.substr(i), &increments));
        }
        // Either +1 or plus the number of converted characters
        i += increments;
    }
    return 0;
}

所以,在这里我们检查字符串的字符。 如果我们找到一个数字,那么我们构建一个字符串的 substring,从当前字符 position 开始,并将其交给std::stoi进行转换。

std::stoi将转换它可以获得的所有字符并将其转换为 int。 如果存在非数字字符,它会停止转换并告知已转换的字符数。 我们将此值添加到评估字符的当前 position 中,以避免一遍又一遍地转换来自相同 integer substring 的数字。

最后,我们将生成的 integer 放入向量中。 我们使用emplace_back来避免不必要的临时值。

这当然适用于有或没有空白。

暂无
暂无

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

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