蓝桥杯 串的处理

来源:互联网 发布:搜狗抢票软件老是退出 编辑:程序博客网 时间:2024/06/10 18:42
串的处理
在实际的开发工作中,对字符串的处理是最常见的编程任务。本题目即是要求程序对用户输入的串进行处理。具体规则如下:
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个字符。


这个题当初学习C++的时候做过,感谢smallgyy

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
    char str1[205],str2[205];
    gets(str1);//可以读入空格
    int len=strlen(str1);
    int i,j,k=0;
    for(i=0,j=0; i<len; i++)//先将多个连续的空格变成1个空格存入str2
    {
        if(str1[i]==' ')
            k++;
        else
        {
            if(k>=1)
            {
                str2[j++]=' ';
                str2[j++]=str1[i];
            }
            else
                str2[j++]=str1[i];
            k=0;
        }
    }
    str2[j]='\0'; //单词首字母大写
    if(str2[0]!=' '&&str2[0]>='a'&&str2[0]<='z')
        str2[0]=str2[0]-32;
    for(i=0; i<=j; i++)
        if(str2[i]==' '&&str2[i+1]>='a'&&str2[i+1]<='z')
            str2[i+1]=str2[i+1]-32;
    for(i=0; i<j; i++)  //输出时同时处理下划线
    {
        if((str2[i]>='A'&&str2[i]<='Z'&&str2[i+1]>='0'&&str2[i+1]<='9')||(str2[i]>='a'&&str2[i]<='z'&&str2[i+1]>='0'&&str2[i+1]<='9'))
            cout<<str2[i]<<"_";
        else if((str2[i]>='0'&&str2[i]<='9'&&str2[i+1]>='A'&&str2[i+1]<='Z')||(str2[i]>='0'&&str2[i]<='9'&&str2[i+1]>='a'&&str2[i+1]<='z'))
            cout<<str2[i]<<"_";
        else
            cout<<str2[i];
    }
    cout<<endl;
    return 0;
}

0 0
原创粉丝点击