【题目链接】
ybt 2047:【例5.16】过滤空格
OpenJudge NOI 1.7 23:过滤多余的空格
【题目考点】
1. 字符数组
2. string类
3. 计数
4. 输入不确定数量的字符串
string s;
while(cin >> s)
{
//...
}
或
char s[105];
while(scanf("%s", s) != EOF))
{
//...
}
OJ上实际是从文件输入,文件末尾是EOF(end of file,实际是-1)。当读到文件末尾时cin >> s
会返回false,scanf("%s", s)
会返回EOF,让循环跳出。
这样的程序在本地调试时,输入n个数据后不会停止。此时可以按Ctrl+Z
,控制台中出现^Z
后,按回车,这样可以结束输入,看到程序运行的结果。
【题解代码】
解法1:遍历字符串的同时构造新的字符串,最后输出
- 使用字符数组
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s_in[205], s_out[205];
cin.getline(s_in, 205);
int len = strlen(s_in), bn = 0, si = 0;//bn:空格数量计数
for(int i = 0; i <= len; ++i)//遍历到'\0'位置
{
if(s_in[i] == ' ')
{
bn++;//空格数量计数加1
if(bn == 1)
s_out[si++] = s_in[i];//将s_in[i]填充到s_out中
}
else
{
s_out[si++] = s_in[i];
bn = 0;
}
}
cout << s_out;
return 0;
}
- 使用string类
用到了string类的成员函数push_back,将一个字符添加到字符串末尾
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s_in, s_out;
getline(cin, s_in);
int bn = 0;//bn:空格数量计数
for(int i = 0; i < s_in.length(); ++i)
{
if(s_in[i] == ' ')
{
bn++;//空格数量计数加1
if(bn == 1)
s_out.push_back(s_in[i]);//将s_in[i]添加到s_out末尾
}
else
{
s_out.push_back(s_in[i]);
bn = 0;
}
}
cout << s_out;
return 0;
}
解法2:遍历字符数组,遇到多余的空格不输出,遇到其它字符输出
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[205];
cin.getline(s, 205);
int len = strlen(s), bn = 0;
for(int i = 0; i < len; ++i)
{
if(s[i] == ' ')
bn++;
else
bn = 0;
if(s[i] != ' ' || bn == 1)
cout << s[i];
}
return 0;
}
解法3:读入不确定数量的字符串
- 使用string
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
while(cin >> s)
cout << s << ' ';
return 0;
}
- 使用scanf
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[205];
while(scanf("%s", s) != EOF)
printf("%s ", s);
return 0;
}