在 c++ 中删除标点符号和空格的最佳方法是什么

What is the best way to remove punctuations and white spaces in c++?

本文关键字:最佳 方法 是什么 空格 c++ 删除 标点符号      更新时间:2023-10-16

为了从给定的字符串中删除空格和标点符号。使用正则表达式匹配似乎是一种方法,但是使用布尔数组[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_ifstd::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)  
                       );