【问题标题】:Want to remove \n\t whitespace from my string c++ [duplicate]想从我的字符串 C++ 中删除 \n\t 空格 [重复]
【发布时间】:2021-03-04 12:05:40
【问题描述】:

我需要从输入字符串中删除“\n\t”?

例如,

"lorenda bianco"
<loredana.bianco@yahoo.co.jp>

对我来说是无效的输入。 (只是\n)

"lorenda bianco"
    <loredana.bianco@yahoo.co.jp>

对我来说是有效的输入。 (\n\t)。

我尝试使用 isspace,但不知道如何组合不同的空格。

我希望我的输出为"lorenda bianco" &lt;loredana.bianco@yahoo.co.jp&gt;

我可以在@404 的帮助下摆脱“\n”。但是,\t 既不适用于他的解决方案,也不适用于擦除/删除。 我也试图删除 \t :

s.erase(std::remove_if(s.begin(), s.end(), '\t'), s.end());

不知何故不起作用。但是当我打印它时,它会显示 4 个单独的空格而不是单个选项卡。可能这就是它不起作用的原因。它需要单个制表符而不是 4 个连续的空格字符。不知道怎么破解。

--- 尝试从字符串中删除 \n\t 失败(\n 有效,但 \t 仍然存在)

str before ws removal: "lorenda bianco"
<loredana.bianco@yahoo.co.jp>

删除ws后的str:“lorenda bianco”loredana.bianco@yahoo.co.jp

【问题讨论】:

  • 使用 C++ string::replace 可能会有所帮助。 cplusplus.com/reference/string/string/replace
  • 请提供A Minimal, Complete, and Verifiable Example (MCVE)。任何人都很难在没有看到您如何尝试阅读和存储信息的情况下做出结论性的回答。没有看到更多find_first_not_of 的组合使用whitespace,然后使用erasesubstr 似乎可行的方法来做到这一点。
  • 更新了有问题的示例输出。
  • @Elliott 缩进在这里搞砸了。 \t 不起作用。简而言之,您的解决方案 \n 被删除,但不是 \t。
  • 正如大卫所说,最佳实践是使用minimal, complete and verifiable working example。根据我在这里阅读的内容,我无法重现您的问题。

标签: c++ whitespace mime


【解决方案1】:
#include <iostream>

int main()
{
    std::string myString = "lorenda bianco\n\t <loredana.bianco@yahoo.co.jp>";

    std::cout << "Before changing: \"" << myString << "\"\n";


    for (int i=0; i < myString.length(); i++){
            if ( myString[i] == '\n'){
                myString.erase(i, 1);
                i -= 1;
            }
            if ( myString[i] == '\t'){
                myString.erase(i, 1);
                i -= 1;
            }

    }


    std::cout << "After changing: \"" << myString << "\"\n";

    return 0;
}

【讨论】:

  • @Elliott:实际上,我只想根据 MIME 要求将 \n\t 作为组合删除。现在单独删除 \n 或 \t 对我来说并不重要。
  • 那应该可以工作了——第二个sn-p代码。如果组合超过 1 个,则在运行 if 语句后删除 break 并从 i 中减去 2
  • 伙计们,\n 与@404TNF 解决方案一起工作正常。但是 \t 不起作用。当我打印它时,它显示了 4 个单独的空格。不考虑 4 个空格的单个组合。
  • @404TNF,抱歉,该代码中仍有错误。 for (int... 应该是 for (unsigned... 另外,您的第二个 if 应该是 else if。上述代码崩溃的示例:myString = "\n"
  • @404TNF,这是一个如何修复它的示例,它不需要--i,然后是++icodeshare.io/5R3dOL
猜你喜欢
  • 2019-10-24
  • 2014-02-13
  • 1970-01-01
  • 2014-04-01
  • 2015-01-13
  • 2012-05-06
  • 1970-01-01
  • 2020-08-06
  • 2019-09-10
相关资源
最近更新 更多