【问题标题】:Replace tabs in a string with several spaces用多个空格替换字符串中的制表符
【发布时间】:2021-08-24 15:43:39
【问题描述】:

任何人都可以建议一种用多个空格(例如“”(4 个空格))替换 std::string 中的制表符的好方法吗?

我尝试使用此代码,但无法替换它们:

std::regex_replace(cinput, std::regex("[ \t]"), " ");

【问题讨论】:

  • 您想要替换副本,还是要就地替换?
  • @AyxanHaqverdili 任何一个都可以,只要它输出一个没有制表符的字符串

标签: c++ regex string


【解决方案1】:

你可以使用replace():

#include <iostream>
#include <string>
using namespace std;

int main ()
{
    string x = "abc\tdef\ttest";
    cout << x << "\n";

    string fi = "\t"; //tab
    string se = "    "; //four spaces

    auto it = x.find(fi);
    while (it != string::npos)
    {
        x.replace(it, fi.size(), se);
        it = x.find(fi);
    }
    cout << x;
}

输出:

abc     def     test
abc    def    test

或者在您的示例中使用regex_replace()

#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main ()
{
    string x = "abc\tdef\ttest";
    cout << x << "\n";

    string fi = "\t"; //tab
    string se = "%%"; //some test characters, you can switch back to four spaces

    x = regex_replace(x, std::regex(fi), se);
    cout << x;
}

输出:

abc     def     test
abc%%def%%test

【讨论】:

    【解决方案2】:

    是的,您可以使用std::regex 来做到这一点:

    #include <iostream>
    #include <iterator>
    #include <regex>
    #include <string>
    
    int main() {
      std::string const text = "Quick\tbrown\tfox";
      std::string output;
      std::regex const tab(R"(\t)");
    
      std::regex_replace(back_inserter(output), begin(text), end(text), tab,
                         "    " /* 4 spaces */);
    
      std::cout << '\n' << output << '\n';
    }
    

    Demo

    请注意,std::regex 实现的编译和运行速度都非常慢。您可能对 Boost.RegexCTRE 等其他正则表达式库感兴趣。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-11
      • 2011-09-04
      • 2011-09-15
      • 2013-05-09
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      相关资源
      最近更新 更多