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

Extracting integers from a string which has no space

本文关键字:提取 整数 字符串 空格      更新时间:2023-10-16

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

#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;
}

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

std::stoi将转换它可以获得的所有字符,并将其转换为整数。如果存在非数字字符,它将停止转换并通知已转换的字符数。我们将此值添加到计算字符的当前位置,以避免一遍又一遍地转换同一整数子字符串中的数字。

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

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