经期去除剂后的双倍空格
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;
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 如何在c++中使用system()来运行包含空格的python脚本
- basic_string的前导/尾部不区分空格的特征
- 移除前面有空格的前2个字符串
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 在字符串中插入空格
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- C++为一串单词添加空格
- 使用另一个字符串从字符串中删除空格
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 如何打印不带空格的输入整数?
- 野牛/yacc 解析器在不被空格分隔时跳过 grammer - "unexpected $end"
- C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?
- 在 c++ 中逐行阅读字符串,不要以空格停止