从没有空格的字符串中提取整数
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;
}
因此,在这里我们检查字符串的字符。如果我们找到一个数字,那么我们构建字符串的子字符串,从当前字符位置开始,并将其交给std::stoi
进行转换。
std::stoi
将转换它可以获得的所有字符,并将其转换为整数。如果存在非数字字符,它将停止转换并通知已转换的字符数。我们将此值添加到计算字符的当前位置,以避免一遍又一遍地转换同一整数子字符串中的数字。
最后,我们将生成的整数放入向量中。我们使用emplace_back
来避免不必要的临时价值。
这当然适用于有或没有空白。
相关文章:
- 从字符串中提取整数并形成一个数组
- 从没有空格的字符串中提取整数
- C++从字符串中提取整数
- 从QString中提取整数
- 从字符串中提取整数
- 使用C 从定界线拆分字符串中提取整数数组
- 从用户输入中提取整数的枚举开关语句
- 如何从两个字符之间的文件中提取整数
- 从字符串中提取整数
- 如何从字符串中提取整数?C++
- 提取整数的数字元素
- C++:从字符串对象中提取整数
- 从标准::字符串中提取整数
- 使用字符串流从 c++ 中的字符串中提取整数时意外重复
- 从隐藏在随机字符之间的文件中提取整数
- C++ 使用 cin.ignore() 提取整数时输出奇怪
- 如何使用toInt从Qt中的QByteArray中提取整数
- 如何从C风格的constchar*数组中提取整数
- 从字符串中提取整数
- 提取整数余数的最佳方法