don*_*ton 0 c++ string parsing split atoi
这似乎是一个应该很容易搜索的问题,但任何答案似乎都被大量问题淹没了,这些问题提出了将字符串转换为整数的更常见问题。
我的问题是:什么是一个简单的方法来从提取物整数std::strings
可能看起来像"abcd451efg"
或"hel.lo42-world!"
或"hide num134rs here?"
我看到,我可以使用isDigit
手动解析字符串自己,但我不知道是否存在的静脉更标准的方式atoi
或stoi
等.
上面的输出将是 451、42 和 134。我们还可以假设字符串中只有一个整数(尽管通用解决方案不会有什么坏处)。所以我们不必担心像"abc123def456"
.
Java 有一个简单的解决方案,形式为
Integer.parseInt(str.replaceAll("[\\D]", ""));
Run Code Online (Sandbox Code Playgroud)
C++ 有这么简单的东西吗?
您可以使用
string::find_first_of("0123456789")
获取第一位数字的位置,然后string::find_last_of("0123456789")
获取最后一位数字的位置,最后atoi
在由两个位置定义的子字符串上使用。我想不出更简单的东西(没有正则表达式)。
顺便说一句,这仅在字符串中有一个数字时才有效。
下面是一个例子:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string s = "testing;lasfkj358kdfj-?gt";
size_t begin = s.find_first_of("0123456789");
size_t end = s.find_last_of("0123456789");
string num = s.substr(begin, end - begin + 1);
int result = atoi(num.c_str());
cout << result << endl;
}
Run Code Online (Sandbox Code Playgroud)
如果您有 1 个以上的数字,您可以结合string::find_first_of
使用string::find_first_not_of
以获取字符串中每个数字的开头和结尾。
此代码是一般解决方案:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string s = "testing;lasfkj358kd46fj-?gt"; // 2 numbers, 358 and 46
size_t begin = 0, end = 0;
while(end != std::string::npos)
{
begin = s.find_first_of("0123456789", end);
if(begin != std::string::npos) // we found one
{
end = s.find_first_not_of("0123456789", begin);
string num = s.substr(begin, end - begin);
int number = atoi(num.c_str());
cout << number << endl;
}
}
}
Run Code Online (Sandbox Code Playgroud)