【问题标题】:How to epur a std::string in c++?如何在 C++ 中使用 std::string?
【发布时间】:2012-07-20 20:29:54
【问题描述】:

我会知道不使用使用 boost 的 std::string 最好和最简单的方法。

例如如何转换这个字符串

"  a   b          c  d     e '\t' f      '\t'g"

"a b c d e f g"

假设 '\t' 是一个正常的制表。

谢谢。

【问题讨论】:

  • 什么是epur
  • 我不确定“epur”是什么意思。你能解释一下吗?
  • 5 分钟内 22 位观众想知道“epur”是什么意思。
  • 你试过什么?真的,它只需要在字符串上进行一两个循环和一些逻辑来跟踪复制源和复制到偏移量....
  • 或者它来自法语épurer,“expurgate”?

标签: c++ string algorithm


【解决方案1】:

使用字符串流的惰性解决方案:

#include <string>
#include <sstream>

std::istringstream iss(" a b c d e \t f \tg");
std::string w, result;

if (iss >> w) { result += w; }
while (iss >> w) { result += ' ' + w; }

// now use `result`

【讨论】:

    【解决方案2】:

    您没有定义“epur”的含义,但该示例使您看起来像您想要的那样删除前导(和尾随?)空格并用单个空格替换内部空格。现在您可以使用 std::replace_if、std::uniqiue 和 std::copy_if 的组合来执行此操作,但这非常复杂,并且最终会多次复制数据。如果你想在原地单次通过,一个简单的循环可能是最好的:

    void epur(std::string &s)
    {
      bool space = false;
      auto p = s.begin();
      for (auto ch : s)
        if (std::isspace(ch)) {
          space = p != s.begin();
        } else {
          if (space) *p++ = ' ';
          *p++ = ch;
          space = false; }
      s.erase(p, s.end());
    }
    

    【讨论】:

      【解决方案3】:

      您似乎想从字符串中删除 \t 字符。您可以通过复制不是\t 的字符来执行此操作,如下所示:

      #include <iostream>
      #include <string>
      #include <algorithm>
      #include <iterator>
      
      int main() 
      {
        std::string s1( "a b c \t d e f \t" );
        std::string s2;
      
        std::copy_if( std::begin(s1), 
                      std::end(s1), 
                      std::back_inserter<std::string>(s2),
                      [](std::string::value_type c) {
                          return c != '\t';
                      } );
      
        std::cout << "Before: \"" << s1 << "\"\n";
        std::cout << "After: \"" << s2 << "\"\n";
      }
      

      输出:

      Before: "a b c   d e f  "
      After: "a b c  d e f "
      

      如果要删除字符串中的所有空格,请将return 语句替换为

      return !std::isspace(c);
      

      (isspace 在标题 cctype)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-22
        • 2010-12-04
        • 1970-01-01
        • 2020-11-04
        • 1970-01-01
        • 1970-01-01
        • 2021-07-31
        • 1970-01-01
        相关资源
        最近更新 更多