经期去除剂后的双倍空格

Double space after period remover

本文关键字:空格      更新时间:2023-10-16

在文字处理器之前学会如何打字的人通常会在句子结尾的句点后添加两个空格。编写一个函数 singleSpaces,该函数接受一个字符串,并将该字符串(在 "." 之后出现两个空格的所有位置)返回到更改的单个空格中。

这就是我所拥有的;我做错了什么?

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

string forceSingleSpaces1 (string s) {
    string r = "";
    int i = 0;
    while (i < static_cast <int> (s.length()))  {
        if (s.at(i) != ' ')  {
            r = r + s.at(i);
            i++;
        } else  {
            r +=  ' ';
            while (i < static_cast <int> (s.length()) && s.at(i) == ' ')
                i++;
        }
    }
    return r;
}

在你的作业中,有关于点后双倍空格的讨论,而不是文本中的所有双倍空格。所以你应该修改你的代码,以便它

  • 等待"."而不是" ',
  • 当"."被截获时,添加它,然后添加任何单个空格

您可以将此代码视为两个状态机:

状态 1 - 当您循环任何非 '." 字符时,在此状态下,您的代码会将它找到的所有内容添加到结果中

状态 2 - 当找到 '." 时,在此状态下您使用不同的代码,将 '." 添加到结果中并恰好是单个空格(如果找到任何一个)

这样,您将问题分为两个子问题

[编辑] - 用修改提示替换源代码

您可以(重新)使用更通用的函数,该函数将字符串中给定字符串的出现替换为另一个字符串,如此处所述。

#include <string>
#include <iostream>
void replace_all(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
}
int main() {
    std::string text = "I'm old.  And I use two spaces.  After periods.";
    std::string newstyle_text(text);
    replace_all(newstyle_text, ".  ", ". ");
    std::cout << newstyle_text << "n";
    return 0;
}

更新

如果您不怕走在最前沿,则可以考虑使用 TR1 正则表达式。这样的事情应该有效:

#include <string>
#include <regex>
#include <iostream>
int main() {
    std::string text = "I'm old.  And I use two spaces.  After periods.";
    std::regex regex = ".  ";
    std::string replacement = ". ";
    std::string newstyle_text = std::regex_replace(text, regex, repacement);
    std::cout << newstyle_text << "n";
    return 0;
}
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
//1. loop through the string looking for ".  "
//2. when ".  " is found, delete one of the spaces
//3. Repeat process until ".  " is not found.  
string forceSingleSpaces1 (string str) {
    size_t found(str.find(".  "));
    while (found !=string::npos){
        str.erase(found+1,1);
        found = str.find(".  ");
    }
    return str;
}
int main(){
    cout << forceSingleSpaces1("sentence1.  sentence2.  end.  ") << endl;
    return EXIT_SUCCESS;
}