簡體   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