【问题标题】:Removing leading and trailing spaces from a string从字符串中删除前导和尾随空格
【发布时间】:2009-11-25 16:22:37
【问题描述】:

如何在 C++ 中从字符串对象中删除空格。
例如,如何从下面的字符串对象中删除前导和尾随空格。

//Original string: "         This is a sample string                    "
//Desired string: "This is a sample string"

据我所知,字符串类没有提供任何删除前导和尾随空格的方法。

为了增加问题,如何扩展此格式以处理字符串单词之间的额外空格。例如,

// Original string: "          This       is         a sample   string    " 
// Desired string:  "This is a sample string"  

使用解决方案中提到的字符串方法,我可以考虑分两步进行这些操作。

  1. 删除前导和尾随空格。
  2. 在单词边界处重复使用 find_first_of、find_last_of、find_first_not_of、find_last_not_of 和 substr,以获得所需的格式。

【问题讨论】:

    标签: c++ string


    【解决方案1】:

    这称为修剪。如果你可以使用Boost,我会推荐它。

    否则,使用find_first_not_of 获取第一个非空白字符的索引,然后使用find_last_not_of 获取末尾不是空格的索引。有了这些,使用substr 来获取没有周围空格的子字符串。

    针对您的编辑,我不知道该术语,但我猜想类似于“减少”的内容,所以我就是这么称呼它的。 :)(注意,为了灵活性,我已将空格更改为参数)

    #include <iostream>
    #include <string>
    
    std::string trim(const std::string& str,
                     const std::string& whitespace = " \t")
    {
        const auto strBegin = str.find_first_not_of(whitespace);
        if (strBegin == std::string::npos)
            return ""; // no content
    
        const auto strEnd = str.find_last_not_of(whitespace);
        const auto strRange = strEnd - strBegin + 1;
    
        return str.substr(strBegin, strRange);
    }
    
    std::string reduce(const std::string& str,
                       const std::string& fill = " ",
                       const std::string& whitespace = " \t")
    {
        // trim first
        auto result = trim(str, whitespace);
    
        // replace sub ranges
        auto beginSpace = result.find_first_of(whitespace);
        while (beginSpace != std::string::npos)
        {
            const auto endSpace = result.find_first_not_of(whitespace, beginSpace);
            const auto range = endSpace - beginSpace;
    
            result.replace(beginSpace, range, fill);
    
            const auto newStart = beginSpace + fill.length();
            beginSpace = result.find_first_of(whitespace, newStart);
        }
    
        return result;
    }
    
    int main(void)
    {
        const std::string foo = "    too much\t   \tspace\t\t\t  ";
        const std::string bar = "one\ntwo";
    
        std::cout << "[" << trim(foo) << "]" << std::endl;
        std::cout << "[" << reduce(foo) << "]" << std::endl;
        std::cout << "[" << reduce(foo, "-") << "]" << std::endl;
    
        std::cout << "[" << trim(bar) << "]" << std::endl;
    }
    

    结果:

    [too much               space]  
    [too much space]  
    [too-much-space]  
    [one  
    two]  
    

    【讨论】:

    • 我假设您的意思是“size_t”。并且您在子字符串上有一个非一,应该是 substr(beginStr, endStr - beginStr + 1);
    • 应该site_tsize_t 吗?我认为你有评论no whitespace 意味着字符串全是空格或空。
    • 谢谢,修正了 size_t 在编辑中的拼写错误,但没有注意到我的评论被颠倒了,谢谢。
    • @GMan 非常优雅的解决方案。谢谢。
    • 错误:尝试通过 trim() 运行“one\ttwo”。结果是一个空字符串。您还需要针对 std::string::npos 测试 endStr。
    【解决方案2】:

    在一行中轻松删除 std::string 中的前导、尾随和额外空格

    value = std::regex_replace(value, std::regex("^ +| +$|( ) +"), "$1");
    

    只删除前导空格

    value.erase(value.begin(), std::find_if(value.begin(), value.end(), std::bind1st(std::not_equal_to<char>(), ' ')));
    

    value = std::regex_replace(value, std::regex("^ +"), "");
    

    只删除尾随空格

    value.erase(std::find_if(value.rbegin(), value.rend(), std::bind1st(std::not_equal_to<char>(), ' ')).base(), value.end());
    

    value = std::regex_replace(value, std::regex(" +$"), "");
    

    只删除多余的空格

    value = regex_replace(value, std::regex(" +"), " ");
    

    【讨论】:

    • 不错的一个。提供一些关于这里发生的事情的信息会很有用,因为很难理解这些代码。
    • 不过,仅适用于 C++11。
    • 它不会删除标签,但这可以修复。无法修复的是它非常慢(比substrerase 的答案慢约100 倍)。
    • 对于速度优化,正则表达式不是最佳解决方案,但可以通过创建一次正则表达式实例来改进
    【解决方案3】:

    我目前正在使用这些功能:

    // trim from left
    inline std::string& ltrim(std::string& s, const char* t = " \t\n\r\f\v")
    {
        s.erase(0, s.find_first_not_of(t));
        return s;
    }
    
    // trim from right
    inline std::string& rtrim(std::string& s, const char* t = " \t\n\r\f\v")
    {
        s.erase(s.find_last_not_of(t) + 1);
        return s;
    }
    
    // trim from left & right
    inline std::string& trim(std::string& s, const char* t = " \t\n\r\f\v")
    {
        return ltrim(rtrim(s, t), t);
    }
    
    // copying versions
    
    inline std::string ltrim_copy(std::string s, const char* t = " \t\n\r\f\v")
    {
        return ltrim(s, t);
    }
    
    inline std::string rtrim_copy(std::string s, const char* t = " \t\n\r\f\v")
    {
        return rtrim(s, t);
    }
    
    inline std::string trim_copy(std::string s, const char* t = " \t\n\r\f\v")
    {
        return trim(s, t);
    }
    

    【讨论】:

      【解决方案4】:

      Boost string trim algorithm

      #include <boost/algorithm/string/trim.hpp>
      
      [...]
      
      std::string msg = "   some text  with spaces  ";
      boost::algorithm::trim(msg);
      

      【讨论】:

        【解决方案5】:

        这是我去除前导和尾随空格的解决方案...

        std::string stripString = "  Plamen     ";
        while(!stripString.empty() && std::isspace(*stripString.begin()))
            stripString.erase(stripString.begin());
        
        while(!stripString.empty() && std::isspace(*stripString.rbegin()))
            stripString.erase(stripString.length()-1);
        

        结果是“Plamen”

        【讨论】:

        • 这是一个真的次优的解决方案。在字符串开头的每个erase 调用都会导致字符串的每个字符都被洗牌1——这对于大字符串来说是非常昂贵的。最好找到第一个不是空格字符的字符,然后擦除直到该点的部分。
        【解决方案6】:

        你可以这样做:

        std::string & trim(std::string & str)
        {
           return ltrim(rtrim(str));
        }
        

        支持功能实现为:

        std::string & ltrim(std::string & str)
        {
          auto it2 =  std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
          str.erase( str.begin() , it2);
          return str;   
        }
        
        std::string & rtrim(std::string & str)
        {
          auto it1 =  std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
          str.erase( it1.base() , str.end() );
          return str;   
        }
        

        一旦你准备好所有这些,你也可以这样写:

        std::string trim_copy(std::string const & str)
        {
           auto s = str;
           return ltrim(rtrim(s));
        }
        

        【讨论】:

          【解决方案7】:

          按照 jon-hanson 的建议使用 boost 来修剪前导和尾随空格的示例(仅删除尾随和未决空格):

          #include <boost/algorithm/string/trim.hpp>
          
          std::string str = "   t e s t    ";
          
          boost::algorithm::trim ( str );
          

          "t e s t" 中的结果

          还有

          • trim_left 导致 "t e s t "
          • trim_right 导致 " t e s t"

          【讨论】:

            【解决方案8】:
            /// strip a string, remove leading and trailing spaces
            void strip(const string& in, string& out)
            {
                string::const_iterator b = in.begin(), e = in.end();
            
                // skipping leading spaces
                while (isSpace(*b)){
                    ++b;
                }
            
                if (b != e){
                    // skipping trailing spaces
                    while (isSpace(*(e-1))){
                        --e;
                    }
                }
            
                out.assign(b, e);
            }
            

            在上面的代码中,isSpace()函数是一个布尔函数,判断一个字符是否为空格,你可以实现这个函数来反映你的需要,或者只是从“ctype.h”中调用isspace()如果你愿意。

            【讨论】:

              【解决方案9】:

              修剪前导和尾随空格的示例

              std::string aString("    This is a string to be trimmed   ");
              auto start = aString.find_first_not_of(' ');
              auto end = aString.find_last_not_of(' ');
              std::string trimmedString;
              trimmedString = aString.substr(start, (end - start) + 1);
              

              trimmedSring = aString.substr(aString.find_first_not_of(' '), (aString.find_last_not_of(' ') - aString.find_first_not_of(' ')) + 1);
              

              【讨论】:

              • 人们不会喜欢查看 10 页代码来学习如何修剪字符串。
              • 如果字符串只有空格就坏了
              【解决方案10】:

              使用标准库有很多好处,但必须注意一些会导致异常的特殊情况。例如,没有一个答案涵盖 C++ 字符串包含一些 Unicode 字符的情况。在这种情况下,如果你使用函数isspace,就会抛出异常。

              我一直在使用以下代码来修剪字符串和其他一些可能会派上用场的操作。这段代码的主要好处是:它非常快(比我测试过的任何代码都快),它只使用标准库,并且永远不会引发异常:

              #include <string>
              #include <algorithm>
              #include <functional>
              #include <locale>
              #include <iostream>
              
              typedef unsigned char BYTE;
              
              std::string strTrim(std::string s, char option = 0)
              {
                  // convert all whitespace characters to a standard space
                  std::replace_if(s.begin(), s.end(), (std::function<int(BYTE)>)::isspace, ' ');
              
                  // remove leading and trailing spaces
                  size_t f = s.find_first_not_of(' ');
                  if (f == std::string::npos) return "";
                  s = s.substr(f, s.find_last_not_of(' ') - f + 1);
              
                  // remove consecutive spaces
                  s = std::string(s.begin(), std::unique(s.begin(), s.end(),
                      [](BYTE l, BYTE r){ return l == ' ' && r == ' '; }));
              
                  switch (option)
                  {
                  case 'l':  // convert to lowercase
                      std::transform(s.begin(), s.end(), s.begin(), ::tolower);
                      return s;
                  case 'U':  // convert to uppercase
                      std::transform(s.begin(), s.end(), s.begin(), ::toupper);
                      return s;
                  case 'n':  // remove all spaces
                      s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
                      return s;
                  default: // just trim
                      return s;
                  }
              }
              

              【讨论】:

              • C isspace() 的 Unicode 问题是正确的,但如果您使用来自 #include &lt;locale&gt;std::isspace() 则不是 - 然后您可以使用例如isspace(chr, std::locale("en_US.UTF8")).
              【解决方案11】:

              这可能是最简单的。

              您可以使用string::findstring::rfind 从两边查找空格并减少字符串。

              void TrimWord(std::string& word)
              {
                  if (word.empty()) return;
              
                  // Trim spaces from left side
                  while (word.find(" ") == 0)
                  {
                      word.erase(0, 1);
                  }
              
                  // Trim spaces from right side
                  size_t len = word.size();
                  while (word.rfind(" ") == --len)
                  {
                      word.erase(len, len + 1);
                  }
              }
              

              【讨论】:

                【解决方案12】:

                为了补充问题,如何扩展此格式以处理字符串单词之间的额外空格。

                实际上,这比考虑多个前导和尾随空白字符更简单。您需要做的就是从整个字符串中删除重复的相邻空白字符。

                相邻空格的谓词只是:

                auto by_space = [](unsigned char a, unsigned char b) {
                    return std::isspace(a) and std::isspace(b);
                };
                

                然后您可以使用std::unique 和erase-remove 习惯用法删除那些重复的相邻空白字符:

                // s = "       This       is       a sample   string     "  
                s.erase(std::unique(std::begin(s), std::end(s), by_space), 
                        std::end(s));
                // s = " This is a sample string "  
                

                这确实可能会在前面和/或后面留下一个额外的空白字符。这可以很容易地删除:

                if (std::size(s) && std::isspace(s.back()))
                    s.pop_back();
                
                if (std::size(s) && std::isspace(s.front()))
                    s.erase(0, 1);
                

                这是demo

                【讨论】:

                  【解决方案13】:

                  C++17 引入了std::basic_string_view,这是一个类模板,它引用了类似 char 的对象的连续连续序列,即字符串的视图。除了具有与std::basic_string 非常相似的界面外,它还有两个附加功能:remove_prefix(),通过向前移动视图来缩小视图;和 remove_suffix(),通过向后移动视图的末端来缩小视图。这些可用于修剪前导和尾随空格:

                  #include <string_view>
                  #include <string>
                  
                  std::string_view ltrim(std::string_view str)
                  {
                      const auto pos(str.find_first_not_of(" \t\n\r\f\v"));
                      str.remove_prefix(std::min(pos, str.length()));
                      return str;
                  }
                  
                  std::string_view rtrim(std::string_view str)
                  {
                      const auto pos(str.find_last_not_of(" \t\n\r\f\v"));
                      str.remove_suffix(std::min(str.length() - pos - 1, str.length()));
                      return str;
                  }
                  
                  std::string_view trim(std::string_view str)
                  {
                      str = ltrim(str);
                      str = rtrim(str);
                      return str;
                  }
                  
                  int main()
                  {
                      std::string str = "   hello world   ";
                      auto sv1{ ltrim(str) };  // "hello world   "
                      auto sv2{ rtrim(str) };  // "   hello world"
                      auto sv3{ trim(str) };   // "hello world"
                  
                      //If you want, you can create std::string objects from std::string_view objects
                      std::string s1{ sv1 };
                      std::string s2{ sv2 };
                      std::string s3{ sv3 };
                  }
                  

                  注意:使用std::min 来确保pos 不大于size(),当字符串中的所有字符都是空格并且find_first_not_of 返回npos 时会发生这种情况。此外,std::string_view 是非拥有引用,因此它仅在原始字符串仍然存在时才有效。修剪字符串视图对其所基于的字符串没有影响。

                  【讨论】:

                  • 代码示例的最后一部分应该是 ` //如果你愿意,你可以从 std::string_view 对象创建 std::string 对象 std::string s1{ sv1 };标准::字符串 s2{ sv2 };标准::字符串 s3{ sv3 }; ` 或 s1、s2 和 s3 将保留 std::string_view 副本。
                  • @BoR 正确。感谢您指出了这一点。以上更新。
                  【解决方案14】:

                  我已经测试过了,一切正常。所以这个方法 processInput 只会要求用户输入一些东西。它会返回一个内部没有多余空格的字符串,在开头或结尾也没有多余的空格。希望这可以帮助。 (还放了一大堆评论以使其易于理解)。

                  可以在底部的main()中看到如何实现

                  #include <string>
                  #include <iostream>
                  
                  string processInput() {
                    char inputChar[256];
                    string output = "";
                    int outputLength = 0;
                    bool space = false;
                    // user inputs a string.. well a char array
                    cin.getline(inputChar,256);
                    output = inputChar;
                         string outputToLower = "";
                    // put characters to lower and reduce spaces
                    for(int i = 0; i < output.length(); i++){
                      // if it's caps put it to lowercase
                      output[i] = tolower(output[i]);
                      // make sure we do not include tabs or line returns or weird symbol for null entry array thingy
                      if (output[i] != '\t' && output[i] != '\n' && output[i] != 'Ì') {
                        if (space) {
                          // if the previous space was a space but this one is not, then space now is false and add char
                          if (output[i] != ' ') {
                            space = false;
                            // add the char
                            outputToLower+=output[i];
                          }
                        } else {
                          // if space is false, make it true if the char is a space
                          if (output[i] == ' ') {
                            space = true;
                          }
                          // add the char
                          outputToLower+=output[i];
                        }
                      }
                    }
                    // trim leading and tailing space
                    string trimmedOutput = "";
                    for(int i = 0; i < outputToLower.length(); i++){
                      // if it's the last character and it's not a space, then add it
                      // if it's the first character and it's not a space, then add it
                      // if it's not the first or the last then add it
                      if (i == outputToLower.length() - 1 && outputToLower[i] != ' ' || 
                        i == 0 && outputToLower[i] != ' ' || 
                        i > 0 && i < outputToLower.length() - 1) {
                        trimmedOutput += outputToLower[i];
                      } 
                    }
                    // return
                    output = trimmedOutput;
                    return output;
                  }
                  
                  int main() {
                    cout << "Username: ";
                    string userName = processInput();
                    cout << "\nModified Input = " << userName << endl;
                  }
                  

                  【讨论】:

                    【解决方案15】:

                    为什么复杂?

                    std::string removeSpaces(std::string x){
                        if(x[0] == ' ') { x.erase(0, 1); return removeSpaces(x); }
                        if(x[x.length() - 1] == ' ') { x.erase(x.length() - 1, x.length()); return removeSpaces(x); }
                        else return x;
                    }
                    

                    即使 boost 失败,也没有正则表达式,没有奇怪的东西或库,这仍然有效。

                    编辑: 修正 M.M. 的评论。

                    【讨论】:

                    • 与计算空白长度并为每一端使用单个擦除调用相比,这有点低效
                    • edit完全没有来解决这个问题 M.M.提出。
                    【解决方案16】:

                    没有boost,没有regex,只有string 库。就这么简单。

                    string trim(const string s) { // removes whitespace characters from beginnig and end of string s
                        const int l = (int)s.length();
                        int a=0, b=l-1;
                        char c;
                        while(a<l && ((c=s.at(a))==' '||c=='\t'||c=='\n'||c=='\v'||c=='\f'||c=='\r'||c=='\0')) a++;
                        while(b>a && ((c=s.at(b))==' '||c=='\t'||c=='\n'||c=='\v'||c=='\f'||c=='\r'||c=='\0')) b--;
                        return s.substr(a, 1+b-a);
                    }
                    

                    【讨论】:

                    • ...您避免在构建中引入 2M 的头文件!
                    【解决方案17】:

                    可以通过在字符串中使用pop_back() 函数来实现去除前导和尾随空格的恒定时间和空间复杂度。代码如下:

                    void trimTrailingSpaces(string& s) {
                        while (s.size() > 0 && s.back() == ' ') {
                            s.pop_back();
                        }
                    }
                    
                    void trimSpaces(string& s) {
                        //trim trailing spaces.
                        trimTrailingSpaces(s);
                        //trim leading spaces
                        //To reduce complexity, reversing and removing trailing spaces 
                        //and again reversing back
                        reverse(s.begin(), s.end());
                        trimTrailingSpaces(s);
                        reverse(s.begin(), s.end());
                    }
                    

                    【讨论】:

                      【解决方案18】:
                          char *str = (char*) malloc(50 * sizeof(char));
                          strcpy(str, "    some random string (<50 chars)  ");
                      
                          while(*str == ' ' || *str == '\t' || *str == '\n')
                                  str++;
                      
                          int len = strlen(str);
                      
                          while(len >= 0 && 
                                  (str[len - 1] == ' ' || str[len - 1] == '\t' || *str == '\n')
                          {
                                  *(str + len - 1) = '\0';
                                  len--;
                          }
                      
                          printf(":%s:\n", str);
                      

                      【讨论】:

                        【解决方案19】:
                        void removeSpaces(string& str)
                        {
                            /* remove multiple spaces */
                            int k=0;
                            for (int j=0; j<str.size(); ++j)
                            {
                                    if ( (str[j] != ' ') || (str[j] == ' ' && str[j+1] != ' ' ))
                                    {
                                            str [k] = str [j];
                                            ++k;
                                    }
                        
                            }
                            str.resize(k);
                        
                            /* remove space at the end */   
                            if (str [k-1] == ' ')
                                    str.erase(str.end()-1);
                            /* remove space at the begin */
                            if (str [0] == ' ')
                                    str.erase(str.begin());
                        }
                        

                        【讨论】:

                          【解决方案20】:
                          string trim(const string & sStr)
                          {
                              int nSize = sStr.size();
                              int nSPos = 0, nEPos = 1, i;
                              for(i = 0; i< nSize; ++i) {
                                  if( !isspace( sStr[i] ) ) {
                                      nSPos = i ;
                                      break;
                                  }
                              }
                              for(i = nSize -1 ; i >= 0 ; --i) {
                                  if( !isspace( sStr[i] ) ) {
                                      nEPos = i;
                                      break;
                                  }
                              }
                              return string(sStr, nSPos, nEPos - nSPos + 1);
                          }
                          

                          【讨论】:

                            【解决方案21】:

                            对于前导和尾随空格,如何:

                            string string_trim(const string& in) {
                            
                                stringstream ss;
                                string out;
                                ss << in;
                                ss >> out;
                                return out;
                            
                            }
                            

                            或者对于一个句子:

                            string trim_words(const string& sentence) {
                                stringstream ss;
                                ss << sentence;
                                string s;
                                string out;
                            
                                while(ss >> s) {
                            
                                    out+=(s+' ');
                                }
                                return out.substr(0, out.length()-1);
                            }
                            

                            【讨论】:

                              【解决方案22】:

                              干净整洁

                               void trimLeftTrailingSpaces(string &input) {
                                      input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
                                          return !isspace(ch);
                                      }));
                                  }
                              
                                  void trimRightTrailingSpaces(string &input) {
                                      input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
                                          return !isspace(ch);
                                      }).base(), input.end());
                                  }
                              

                              【讨论】:

                                【解决方案23】:

                                我不使用任何STL方法而只使用C++字符串自己的方法解决这个问题的方法如下:

                                void processString(string &s) {
                                    if ( s.empty() ) return;
                                
                                    //delete leading and trailing spaces of the input string
                                    int notSpaceStartPos = 0, notSpaceEndPos = s.length() - 1;
                                    while ( s[notSpaceStartPos] == ' ' ) ++notSpaceStartPos;
                                    while ( s[notSpaceEndPos] == ' ' ) --notSpaceEndPos;
                                    if ( notSpaceStartPos > notSpaceEndPos ) { s = ""; return; }
                                    s = s.substr(notSpaceStartPos, notSpaceEndPos - notSpaceStartPos + 1);
                                
                                    //reduce multiple spaces between two words to a single space 
                                    string temp;
                                    for ( int i = 0; i < s.length(); i++ ) {
                                        if ( i > 0 && s[i] == ' ' && s[i-1] == ' ' ) continue;
                                        temp.push_back(s[i]);
                                    }
                                    s = temp;
                                }
                                

                                我已经用这个方法传递了一个LeetCode问题Reverse Words in a String

                                【讨论】:

                                  【解决方案24】:
                                  void TrimWhitespaces(std::wstring& str)
                                  {
                                      if (str.empty())
                                          return;
                                  
                                      const std::wstring& whitespace = L" \t";
                                      std::wstring::size_type strBegin = str.find_first_not_of(whitespace);
                                      std::wstring::size_type strEnd = str.find_last_not_of(whitespace);
                                  
                                      if (strBegin != std::wstring::npos || strEnd != std::wstring::npos)
                                      {
                                          strBegin == std::wstring::npos ? 0 : strBegin;
                                          strEnd == std::wstring::npos ? str.size() : 0;
                                  
                                          const auto strRange = strEnd - strBegin + 1;
                                          str.substr(strBegin, strRange).swap(str);
                                      }
                                      else if (str[0] == ' ' || str[0] == '\t')   // handles non-empty spaces-only or tabs-only
                                      {
                                          str = L"";
                                      }
                                  }
                                  
                                  void TrimWhitespacesTest()
                                  {
                                      std::wstring EmptyStr = L"";
                                      std::wstring SpacesOnlyStr = L"    ";
                                      std::wstring TabsOnlyStr = L"           ";
                                      std::wstring RightSpacesStr = L"12345     ";
                                      std::wstring LeftSpacesStr = L"     12345";
                                      std::wstring NoSpacesStr = L"12345";
                                  
                                      TrimWhitespaces(EmptyStr);
                                      TrimWhitespaces(SpacesOnlyStr);
                                      TrimWhitespaces(TabsOnlyStr);
                                      TrimWhitespaces(RightSpacesStr);
                                      TrimWhitespaces(LeftSpacesStr);
                                      TrimWhitespaces(NoSpacesStr);
                                  
                                      assert(EmptyStr == L"");
                                      assert(SpacesOnlyStr == L"");
                                      assert(TabsOnlyStr == L"");
                                      assert(RightSpacesStr == L"12345");
                                      assert(LeftSpacesStr == L"12345");
                                      assert(NoSpacesStr == L"12345");
                                  }
                                  

                                  【讨论】:

                                    【解决方案25】:

                                    erase-remove idiom 呢?

                                    std::string s("...");
                                    s.erase( std::remove(s.begin(), s.end(), ' '), s.end() );
                                    

                                    对不起。我看到你不想删除 all 空格为时已晚。

                                    【讨论】:

                                    • 您好,既然您知道答案是错误的,您可以根据需要将其删除。这样,您将在此答案上从 DV 中获得您失去的代表:)
                                    猜你喜欢
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2016-10-11
                                    • 1970-01-01
                                    • 2011-10-02
                                    相关资源
                                    最近更新 更多