-3

为了从给定的字符串中删除空格和标点符号。使用正则表达式匹配似乎是一种方法,但使用 bool 数组 [256] 并将标点符号和空格的值设置为 true 是否有效。此外,由于这将被多次调用,因此最好将其用作静态数组,但是如何在 char 数组中将 punctions 和 space 的值设置为 true?喜欢写一个单独的静态方法来做到这一点?

4

3 回答 3

3

If you've got C++11, you can do this easily with a lambda.

s.erase(
    std::remove_if(
        s.begin(), s.end(),
        []( unsigned char ch ) { return isspace( ch ) || ispunct( ch ); } ),
    s.end() );

This uses the current global locale.

Without C++11, you'll have to define a functional object (reusable if you're doing this a lot):

struct IsSpaceOrPunct
{
    bool operator()( unsigned char ch ) const
    {
        return isspace( ch ) || ispunct( ch );
    }
};

And use an instance of this in place of the lambda in the C++ expression.

These both use the is... functions in <ctype.h> (which is why they operate on unsigned char—invoking these functions with a char is undefined behavior).

A more general solution would be more along the lines of:

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;

For simple, one of applications, this is overkill (unless you really do need to support the varying locales), but if you do any significant amount of text handling, you'll definitely want to have it. Because of the template, you can get all sorts of predicates for almost no work, just another typedef.

于 2013-10-10T18:01:22.030 回答
2

提供的两个答案将起作用,但是一种不需要转换函数指针的方法:

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);
}); 
于 2013-10-10T17:47:37.650 回答
0

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)  
                       );
于 2013-10-10T17:34:22.473 回答