简体   繁体   English

C++删除标点符号前的所有空格,如果标点符号后不存在则添加空格

[英]C++ Remove all the spaces before punctuation signs and add spaces if none exist after punctuation signs

C++ problem - I need to : C++ 问题 - 我需要:

  • remove all the spaces that come before punctuation signs in a string删除字符串中标点符号之前的所有空格
  • add spaces if none exist after punctuation signs.如果标点符号后不存在空格,则添加空格。 I've found a partial solution using regex which solves the first part of the problem,我找到了使用正则表达式的部分解决方案,它解决了问题的第一部分,

I would appreciate an explanation of how it works and any ideas on how I could modify it to cover the second part of the problem as well.我希望能解释一下它是如何工作的,以及我如何修改它以涵盖问题的第二部分的任何想法。 There are no limitations except I'm not looking for any solutions based on hardcoded strings没有任何限制,除非我不是在寻找基于硬编码字符串的任何解决方案

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;
}

Input example : I would ,if at all possible , like to write this sentence properly .输入示例:如果可能的话,我会喜欢正确地写出这句话。

Desired outcome : I would, if at all possible, like to write this sentence properly.期望的结果:如果可能的话,我会喜欢正确地写下这句话。

Your example matches "one or more spaces" that is followed by period or comma (without matching the period or comma), and replaced those spaces with nothing.您的示例匹配后跟句点或逗号(不匹配句点或逗号)的“一个或多个空格”,并将这些空格替换为空。

This modifies is so the regex matches "any number of spaces, dot or comma, any number of spaces", and replaces the entire match with the dot or comma ($1 refers to the part of the pattern in parens) followed by one space.这修改了正则表达式匹配“任意数量的空格,点或逗号,任意数量的空格”,并将整个匹配替换为点或逗号($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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM