[英]Extracting integers from strings in C++ with arbitrary structure
这似乎是一个应该易于搜索的问题,但那里的所有答案似乎都被一大堆问题淹没了,这些问题询问将字符串转换为整数的更常见的问题。
我的问题是:从std::strings
提取看起来像"abcd451efg"
或"hel.lo42-world!"
整数的简单方法是什么"hel.lo42-world!"
还是"hide num134rs here?"
我看到我可以使用isDigit
自己手动解析字符串,但是我想知道atoi
或stoi
等中是否存在更标准的方法。
上面的输出将是451、42和134。我们还可以假设字符串中只有一个整数(尽管一般的解决方案不会受到损害)。 因此,我们不必担心诸如"abc123def456"
类的字符串。
Java具有以下形式的简单解决方案:
Integer.parseInt(str.replaceAll("[\\D]", ""));
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;
}
如果您有多个数字,则可以将string::find_first_of
与string::find_first_not_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;
}
}
}
即使有尾随的非数字,atoi仍可以从字符串中提取数字
int getnum(const char* str)
{
for(; *str != '\0'; ++str)
{
if(*str >= '0' && *str <= '9')
return atoi(str);
}
return YOURFAILURENUMBER;
}
这是一种方法
#include <algorithm>
#include <iostream>
#include <locale>
#include <string>
int main(int, char* argv[])
{
std::string input(argv[1]);
input.erase(
std::remove_if(input.begin(), input.end(),
[](char c) { return !isdigit(c, std::locale()); }),
input.end()
);
std::cout << std::stoll(input) << '\n';
}
您还可以使用<functional>
库来创建谓词
auto notdigit = not1(
std::function<bool(char)>(
bind(std::isdigit<char>, std::placeholders::_1, std::locale())
)
);
input.erase(
std::remove_if(input.begin(), input.end(), notdigit),
input.end()
);
值得指出的是,到目前为止,其他两个答案对数字校验进行了硬编码,使用isdigit
的locale
版本可确保您的程序将根据当前的全局语言环境识别数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.