从字符串中删除多余空格的程序
a programm which removes excess spaces from a string
我写了一个程序,它应该从字符串中删除多余的空格。但是它只显示空格前的字符。它查找一个空格,并检查后面的字符是否为空格。根据多余的空格,它会在多余的空格上移动其他字符。但是输出非常混乱。
输入:"qwe(2空格)rt(1空格)y"
输出:"qwe(一个空格)rt(一个空格)y"
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main(){
string a;
cin >> a;
int len = a.length();
int new_len=len;
int z,s=0;
for(int i=0; i<new_len; i++){
if(a[i]==' '){
z=i+1;
s=0;
//Assigning the number of excess spaces to s.
while(a[z]==' '){
s++;
z++;
}
//doing the shifting here.
if(s>0){
for(int l=i+1; l<new_len-s; l++){
a[l]=a[s+l];
}
}
new_len-=s;
}
}
cout << a << endl;
cout << a.length();
system("pause");
return 0;
}
您的大部分代码都是半无意义的—当您使用普通的字符串提取器(stream >> string
)时,它会自动跳过所有连续的前导空白,并在第一个空白字符处停止读取。因此,它已经完成了其余代码要完成的几乎所有工作。这就留下了一个更简单的方法来完成相同的任务:
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, " "));
这有一个问题:它会在输出的结尾留下一个额外的空间。如果你不想这样,你可以使用我之前发布的infix_ostream_iterator
。这样,您就可以将上面的内容更改为如下内容:
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
infix_ostream_iterator<std::string>(std::cout, " "));
如果您使用的是c++ 11,那么这样做是多余的-您可以使用正则表达式。像下面这样的代码应该可以做到(未经测试):
#include <regex>
#include <iostream>
#include <string>
using namespace::std;
int main(){
string a;
cin >> a;
regex r(" +");
a = regex_replace(a,r," ");
cout << a << endl;
cout << a.length();
system("pause");
return 0;
}
您的代码非常无效。假设下面有一个1,000,000个字符的字符串:
a a a a a a a...
每当你的算法遇到第二个空格时,它就遍历整个字符串,向左移动一个字符。我会尝试另一种方法:
- 创建两个迭代器,如realPos和charPos。在开始时将它们设置为0。
- 创建一个变量,存储到目前为止遇到的一些空间,如spacesSeen。设置为0
- 现在,当realPos小于整个字符串的长度时:
- 如果
string[realPos] != ' '
和charPos != realPos
,则分配string[charPos] = string[realPos]
。然后将realPos
和charPos
都加1。设置spaceseen为0 - 如果
string[realPos] == ' '
和spacesSeen == 0
,则spacesSeen
加1,复制字符并推进两个迭代器。 - 如果
string[realPos] == ' '
和spacesSeen > 0
,则增加spacesSeen
,然后只增加realPos
。
- 如果
- 现在charPos标记了你的最终字符串结束的地方,调整字符串大小,这样它就结束了。
用更简单的话说,就是一个一个地复制这些字符,并在复制过程中跳过多个空格。
相关文章:
- 用于拆分空格字符串的程序不起作用
- 如何在C++的凯撒密码程序中包含空格?
- 为什么EclipseCDT代码格式化程序有时会在模板参数中引入空格
- 解锈化代码格式化程序删除C++单行中的空格
- 崇高文本 3 - 在终端中编译并运行 C++ 程序(路径包含空格)
- 当使用e时没有空格时,奇怪的程序故障
- 在我的输入中没有空格的情况下,程序工作正常?C++
- 字符串中的空格是否会改变程序解释它的方式
- 使用包含给定空格的路径启动程序
- 我有n个空格,在每个空格中,我可以放置一个数字0到m.编写一个程序来输出所有可能的结果.需要帮助:)
- 为什么我不能在数组程序中使用空格?
- 如何从C++程序中删除多个空格,并放一个空格代替它
- 程序错误:用"%20"替换空格
- 当路径中有空格时,从与Qt应用程序相同的目录启动可执行文件
- 如何让我的程序分开而不是将输入之间的空格计算为整数
- C++ 用户定义的字符串需要包含空格(但程序不允许)
- Eclipse在运行调试器时破坏了带有空格字符的程序参数
- 如何在程序 c++ 结束时留出空格
- 当滥用词包含空格时,程序崩溃
- 如何在C++中随机生成的应用程序中在数字之间留出空格