在 c++ 中删除标点符号和空格的最佳方法是什么
What is the best way to remove punctuations and white spaces in c++?
为了从给定的字符串中删除空格和标点符号。使用正则表达式匹配似乎是一种方法,但是使用布尔数组[256]并将标点符号和空格的值设置为true是否有效。另外,由于这将被多次调用,因此最好将其用作静态数组,但是如何在 char 数组中将点和空格的值设置为 true?比如写一个单独的静态方法来做到这一点?
如果你有 C++11,你可以用 lambda 轻松做到这一点。
s.erase(
std::remove_if(
s.begin(), s.end(),
[]( unsigned char ch ) { return isspace( ch ) || ispunct( ch ); } ),
s.end() );
这将使用当前的全局区域设置。
如果没有 C++11,则必须定义一个功能对象(如果您经常这样做,则可以重复使用(:
struct IsSpaceOrPunct
{
bool operator()( unsigned char ch ) const
{
return isspace( ch ) || ispunct( ch );
}
};
并使用此实例代替C++中的 lambda表达。
它们都使用 <ctype.h>
中的 is...
函数(即为什么它们在unsigned char
上运行 — 调用这些具有char
的函数是未定义的行为(。
更通用的解决方案将更类似于:
template <std::ctype_base::mask m>
class Is
{
std::locale l; // To ensure lifetime of the following...
std::ctype<char> const* ctype;
public:
Is( std::locale const& l = std::locale() )
: l( l )
, ctype( &std::use_facet<std::ctype<char>>( l ) )
{
}
bool operator()( char ch ) const
{
return is( m, ch );
}
};
typedef Is<std::ctype_base::space | std::ctype_base::punct> IsSpaceOrPunct;
对于简单的应用程序之一,这是矫枉过正的(除非您确实需要支持不同的区域设置(,但是如果您这样做任何大量的文本处理,您肯定需要拥有它。 由于模板,您可以获得各种几乎没有工作的谓词,只是另一种类型定义。
提供的两个答案将起作用,但这种方法不需要强制转换函数指针:
std::string text = "some text, here and there. goes up; goes down";
std::string result;
std::remove_copy_if(text.begin(), text.end(), std::back_inserter(result), [](char c)
{
std::locale loc;
return std::ispunct(c, loc) || std::isspace(c, loc);
});
将std::remove_copy_if
与std::ispunct
一起使用
string text ="some text with punctuations",result;
std::remove_copy_if(text.begin(), text.end(),
std::back_inserter(result), //Store output
std::ptr_fun<int, int>(&std::ispunct)
);
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 检测win32服务创建和删除的最佳方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将线程中的数据存储到全局容器的最佳方法?
- 将一系列整数放入类的最佳方法是什么?
- 在派生类中使用基类的私有成员变量的最佳方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 将 pybind11 绑定标记为已弃用的最佳方法
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++中变量混叠的最佳方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?