【问题标题】:C++ Remove all the spaces before punctuation signs and add spaces if none exist after punctuation signsC++删除标点符号前的所有空格,如果标点符号后没有空格,则添加空格
【发布时间】:2021-12-20 09:56:16
【问题描述】:

C++ 问题 - 我需要:

  • 删除字符串中标点符号之前的所有空格
  • 如果标点符号后没有空格,请添加空格。 我找到了一个使用正则表达式的部分解决方案,它解决了问题的第一部分,

我希望能解释一下它的工作原理以及关于如何修改它的任何想法 也涵盖问题的第二部分。除了我不是在寻找任何基于硬编码字符串的解决方案之外,没有任何限制

std::string fix_string(const std::string& str) {
    static const std::regex rgx_pattern("\\s+(?=[\\.,])");
    std::string rtn;
    rtn.reserve(str.size());
    std::regex_replace(std::back_insert_iterator<std::string>(rtn), str.cbegin(), str.cend(), rgx_pattern, "");
    return rtn;
}

输入示例:如果可能的话,我会喜欢正确地写这句话。

期望的结果:如果可能的话,我希望能正确地写下这句话。

【问题讨论】:

  • “删除所有句点” 你确定吗?在您的示例中删除了空格。
  • 谢谢指点,我已经修好了,我的意思是去掉标点符号前的空格,如果没有标点符号后加空格

标签: c++ regex string punctuation


【解决方案1】:

您的示例匹配后跟句号或逗号(不匹配句点或逗号)的“一个或多个空格”,并将这些空格替换为空。

这修改了正则表达式匹配“任意数量的空格,点或逗号,任意数量的空格”,并将整个匹配替换为点或逗号($1 指的是括号中的模式部分),然后是一个空格。

std::string fix_string(const std::string& str) {
    static const std::regex rgx_pattern("\\s*([.,])\\s*");
    std::string rtn;
    rtn.reserve(str.size());
    std::regex_replace(std::back_insert_iterator<std::string>(rtn), str.cbegin(), str.cend(), rgx_pattern, "$1 ");
    return rtn;
}

【讨论】:

  • 哦,我明白了,非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
相关资源
最近更新 更多