C++中类似于Python的strip()函数的功能是什么?

15

Python中有一个非常有用的函数叫做strip()。C++中有类似的函数吗?


https://dev59.com/VEXRa4cB1Zd3GeqPv_a- - Veger
可能是如何修剪std :: string的最佳方法的重复问题。 - David Heffernan
可能是重复的问题:Python去除字符串中的空格 - Marcin
可能是Mimic Python's strip() function in C的重复问题。 - Lazik
boost::trim - sp2danny
4个回答

8

我使用这个:

#include <string>
#include <cctype>

std::string strip(const std::string &inpt)
{
    auto start_it = inpt.begin();
    auto end_it = inpt.rbegin();
    while (std::isspace(*start_it))
        ++start_it;
    while (std::isspace(*end_it))
        ++end_it;
    return std::string(start_it, end_it.base());
}

如果 inpt="\t",则最后一步会抛出“字符串过长”异常。 - xycs
下面提供了一个更安全的版本。 - xycs

7

没有内置的功能;我曾经使用过类似以下代码的东西:

template <std::ctype_base::mask mask>
class IsNot
{
    std::locale myLocale;       // To ensure lifetime of facet...
    std::ctype<char> const* myCType;
public:
    IsNot( std::locale const& l = std::locale() )
        : myLocale( l )
        , myCType( &std::use_facet<std::ctype<char> >( l ) )
    {
    }
    bool operator()( char ch ) const
    {
        return ! myCType->is( mask, ch );
    }
};

typedef IsNot<std::ctype_base::space> IsNotSpace;

std::string
trim( std::string const& original )
{
    std::string::const_iterator right = std::find_if( original.rbegin(), original.rend(), IsNotSpace() ).base();
    std::string::const_iterator left = std::find_if(original.begin(), right, IsNotSpace() );
    return std::string( left, right );
}

它的表现相当不错。(我现在有一个更复杂的版本,可以正确处理UTF-8。)


1
void strip(std::string &str)
{
    if  (str.length() != 0)
    {
    auto w = std::string(" ") ;
    auto n = std::string("\n") ;
    auto r = std::string("\t") ;
    auto t = std::string("\r") ;
    auto v = std::string(1 ,str.front()); 
    while((v == w) || (v==t) || (v==r) || (v==n))
    {
        str.erase(str.begin());
        v = std::string(1 ,str.front());
    }
    v = std::string(1 , str.back()); 
    while((v ==w) || (v==t) || (v==r) || (v==n))
    {
        str.erase(str.end() - 1 );
        v = std::string(1 , str.back());
    }
}

1
它在我这里工作得很好,虽然它没有进行良好的优化,但它可以正确地完成工作。我将其设置为void以便在for_each算法中使用。 - Mhadhbi issam

0
这是在Ferdi Kedef的答案基础上进行改进以使其更加安全。
void strip(std::string& str)
{
    if (str.length() == 0) {
        return;
    }

    auto start_it = str.begin();
    auto end_it = str.rbegin();
    while (std::isspace(*start_it)) {
        ++start_it;
        if (start_it == str.end()) break;
    }
    while (std::isspace(*end_it)) {
        ++end_it;
        if (end_it == str.rend()) break;
    }
    int start_pos = start_it - str.begin();
    int end_pos = end_it.base() - str.begin();
    str = start_pos <= end_pos ? std::string(start_it, end_it.base()) : "";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接