【发布时间】:2013-10-28 18:00:21
【问题描述】:
我有一个像“Hello world 1 2 3”这样的字符串,我想得到一个像“Hello World”这样的字符串。你知道它有什么功能吗?
【问题讨论】:
-
您需要更具体。您是否要排除数字,是否还想要“S123ABC”之类的字符串等等...
-
循环 0-9,用空字符串替换每个实例。在您的示例中,您可能还想修剪前导/尾随空格。
我有一个像“Hello world 1 2 3”这样的字符串,我想得到一个像“Hello World”这样的字符串。你知道它有什么功能吗?
【问题讨论】:
作为第一个近似值,假设您希望删除所有数字并将结果放入一个新字符串中,我将从以下内容开始:
std::remove_copy_if(your_string.begin(), your_string.end(),
std::back_inserter(new_string),
[](unsigned char ch) { return isdigit(ch); });
【讨论】:
isdigit 作为一元谓词传递。
char 签名的实现上(这是大多数),当你传递一个值为负的字符时,它会给出 UB。
char 通常已签名)
从字符串中删除所有数字
string x
x.erase(
std::remove_if(x.begin(), x.end(), &isdigit),
x.end());
【讨论】:
这通常使用std::ctype<char> facet 来对包括空白字符在内的字母数字进行分类:
#include <locale>
#include <functional>
template <class charT = char>
bool digit_removal(charT c, std::locale loc)
{
return std::use_facet<std::ctype<charT>>(loc).is(
std::ctype_base::digit, c);
}
int main()
{
std::string var = "Hello 123";
var.erase(
std::remove_if(var.begin(), var.end(),
std::bind(&digit_removal<char>, std::placeholders::_1, std::locale())),
var.end());
std::cout << var; // "Hello "
}
【讨论】:
bind 部分。这部分可以缩短。