8
votes

Fonction similaire en C ++ à la bande de Python ()?

Il existe une fonction très utile dans Python appelée bande () . Tous les mêmes en C ++?


3 Réponses :


5
votes

Il n'y a rien d'intégré; J'avais l'habitude d'utiliser quelque chose comme ce qui suit: xxx

qui fonctionne assez bien. (J'ai maintenant un grand plus complexe version qui traite correctement UTF-8.)


0 commentaires

1
votes
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 commentaires

Cela fonctionne avec moi bon, il n'est pas bien optimisé mais cela fait le travail correctement. Je l'ai fait vider pour l'utiliser dans l'algorithme de 199.



3
votes

J'utilise ceci:

#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());
}


0 commentaires