串的处理
在实际的开发工作中,对字符串的处理是最常见的编程任务。本题目即是要求程序对用户输入的串进行处理。具体规则如下:
1. 把每个单词的首字母变为大写。
2. 把数字与字母之间用下划线字符(_)分开,使得更清晰
3. 把单词中间有多个空格的调整为1个空格。
例如:
用户输入:
you and me what cpp2005program
则程序输出:
You And Me What Cpp_2005_program
用户输入:
this is a 99cat
则程序输出:
This Is A 99_cat
我们假设:用户输入的串中只有小写字母,空格和数字,不含其它的字母或符号。每个单词间由1个或多个空格分隔。
在实际的开发工作中,对字符串的处理是最常见的编程任务。本题目即是要求程序对用户输入的串进行处理。具体规则如下:
1. 把每个单词的首字母变为大写。
2. 把数字与字母之间用下划线字符(_)分开,使得更清晰
3. 把单词中间有多个空格的调整为1个空格。
例如:
用户输入:
you and me what cpp2005program
则程序输出:
You And Me What Cpp_2005_program
用户输入:
this is a 99cat
则程序输出:
This Is A 99_cat
我们假设:用户输入的串中只有小写字母,空格和数字,不含其它的字母或符号。每个单词间由1个或多个空格分隔。
假设用户输入的串长度不超过200个字符。
不知道大家怎么想的,我的想法是将每一个字符分类,因为在不一样的位置的字符的处理方法是不同的,这里,题目中涉及到四种操作,1.首字母大写,2.删除空格,3.加下划线,4.正常输出。对于这四种情况,可以编四个函数,来判断每一个字符的特点,从而进行不同的操作,具体的分类可以看代码,分的比较详细。
#include<iostream>
#include<cstring>
using namespace std;
bool toUp(char *str,int p)//首字母大写
{
if(str[p]>='a'&&str[p]<='z'&&p==0)//第一个字符就是字母
return true;
if(str[p]>='a'&&str[p]<='z'&&str[p-1]==' ')//左边为空格的
return true;
return false;
}
bool usual(char *str,int p)//正常输出
{
if(str[p]>='0'&&str[p]<='9'&&p==0)//数字是字符串的第一个
return true;
if(str[p]>='a'&&str[p]<='z'&&p!=0)//左右两边都是字母的字母
if(str[p-1]>='a'&&str[p-1]<='z')
if(str[p+1]>='a'&&str[p+1]<='z')
return true;
if(str[p]>='0'&&str[p]<='9'&&p!=0)//左右两边都是数字的数字
if(str[p-1]>='0'&&str[p-1]<='9')
if(str[p+1]>='0'&&str[p+1]<='9')
return true;
if(str[p]>='0'&&str[p]<='9'&&p!=0)//左边是字母的数字
if(str[p-1]>='a'&&str[p-1]<='z')
return true;
if(str[p]>='0'&&str[p]<='9')//右边是字母的数字
if(str[p+1]>='a'&&str[p+1]<='z')
return true;
if(str[p]>='0'&&str[p]<='9'&&p!=0)//左边是空格的数字
if(str[p-1]==' ')
return true;
if(str[p]>='0'&&str[p]<='9'&&p!=0)//右边是空格的数字
if(str[p+1]==' ')
return true;
if(str[p]>='a'&&str[p]<='z'&&p!=0)//左边是数字的字母
if(str[p-1]>='0'&&str[p-1]<='9')
return true;
if(str[p]>='a'&&str[p]<='z')//右边是数字的字母
if(str[p+1]>='0'&&str[p+1]<='9')
return true;
if(str[p]>='a'&&str[p]<='z'&&p!=0)//右边是空格的字母
if(str[p+1]==' '&&str[p-1]!=' ')
return true;
if(str[p]>='0'&&str[p]<='9'&&p!=0)//右边为空字符的数字
if(str[p+1]=='\0')
return true;
if(str[p]>='a'&&str[p]<='z'&&p!=0)//右边为空字符的字母
if(str[p+1]=='\0')
return true;
return false;
}
bool space(char *str,int p)//输出空格
{
if(str[p]==' ')
if(str[p-1]>='a'&&str[p-1]<='z')//空格左边为字符
return true;
if(str[p]==' ')
if(str[p-1]>='0'&&str[p-1]<='9')//空格左边为数字
return true;
return false;
}
bool num_word(char *str,int p)//输出 "_"
{
if(str[p]>='a'&&str[p]<='z')//字母右边为数字
if(str[p+1]>='0'&&str[p+1]<='9')
return 1;
if(str[p]>='0'&&str[p]<='9')//数字右边为字母
if(str[p+1]>='a'&&str[p+1]<='z')
return 1;
return false;
}
int main()
{
char str[210],str0[210];
int i,len,p;
gets(str);
len=strlen(str);
p=0;
for(i=0;i<len;i++)
{
if(toUp(str,i))
{
str0[p++]=str[i]-32;
}
if(usual(str,i)&&!toUp(str,i))
{
str0[p++]=str[i];
}
if(space(str,i))
{
str0[p++]=' ';
}
if(num_word(str,i))
{
str0[p++]='_';
}
}
str0[p]='\0';
cout<<str0;
return 0;
}