首页 > 试题广场 >

首字母大写

[编程题]首字母大写
  • 热度指数:26800 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
对一个字符串中的所有单词,如果单词的首字母不是大写字母,则把单词的首字母变成大写字母。 在字符串中,单词之间通过空白符分隔,空白符包括:空格(' ')、制表符('\t')、回车符('\r')、换行符('\n')。

输入描述:
输入一行:待处理的字符串(长度小于100)。


输出描述:
可能有多组测试数据,对于每组数据,
输出一行:转换后的字符串。
示例1

输入

if so, you already have a google account. you can sign in on the right.

输出

If So, You Already Have A Google Account. You Can Sign In On The Right.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by fhqplzj on 17-2-26 at 下午8:31.
 */
public class Main {
    private static String capitalize(String s) {
        Pattern pattern = Pattern.compile("\\w+");
        Matcher matcher = pattern.matcher(s);
        StringBuffer stringBuffer = new StringBuffer();
        while (matcher.find()) {
            String group = matcher.group();
            String replacement = Character.toUpperCase(group.charAt(0)) + group.substring(1);
            matcher.appendReplacement(stringBuffer, replacement);
        }
        matcher.appendTail(stringBuffer);
        return stringBuffer.toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            System.out.println(capitalize(scanner.nextLine()));
        }
    }
}

编辑于 2017-02-26 22:02:25 回复(0)

python解法如下。


本来准备一行解决的:

# print(" ".join(map(lambda c:c.capitalize(),input().split())))

发现题目中的字符串不是只由空格分隔的,还有可能是制表符,所以这种方法行不通,于是写了另一种方法,通过所有测试。


while True:
    try:
        string=list(input())
        canUpper=True
        for i,v in enumerate(string):
            if v.isalpha() and canUpper:
                string[i]=v.upper()
                canUpper=False
            elif v==" " or v=="\t" or v=="\n" or v=="\r":
                canUpper=True
            else:
                canUpper=False
        print("".join(string))

    except:
        break
发表于 2017-10-16 16:41:52 回复(0)
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
int main()
{
    string str;
    while(getline(cin,str))
    {
//         首字符是否是小写字母,是就大写
        if(str[0]<='z'&&str[0]>='a')
        {
            str[0]-=32;
        }
        
        for(int i=1;i<str.length();i++)
        {
//             当遇到空白符就不管,看后一个字符是否为小写字母
            while(str[i]==' '||str[i]=='\t'||str[i]=='\r'||str[i]=='\n')
            {
                i++;
                if(str[i]<='z'&&str[i]>='a')
                {
                    str[i]-=32;
                    break;
                }
            }
            
        }
        cout<<str<<endl;
    }
}
发表于 2022-02-22 16:10:26 回复(0)
//ASCII码大写字母比相同的小写字母小32
//我这个程序应该是最完整的了,同时可以处理当首字符为空字符时的情况,是程序更具有鲁棒性
#include<iostream>
(720)#include<string>
using namespace std;
int main()
{
    string str;
    while(getline(cin,str))
    {
        if(str[0]!=' '&&str[0]!='\t'&&str[0]!='\r'&&str[0]!='\n'&&str[0]>='a'&&str[0]<='z')
            str[0]-=32;
        for(int i=0;i<str.size()-1;i++)
        {
            if(str[i]==' '||str[i]=='\t'||str[i]=='\r'||str[i]=='\n')
            {
                if(str[i+1]>='a'&&str[i+1]<='z')
                    str[i+1]-=32;
            }
        }
        cout<<str<<endl;
    }
    return 0;
}

发表于 2020-05-01 10:19:56 回复(0)
#include<stdio.h>
int main()
{
    char a[100];
    while(gets(a)!=NULL)
    {
        for(int i=0;a[i]!='\0';i++)
            if((i==0||a[i-1]==' '||a[i-1]=='\t'||a[i-1]=='\r'||a[i-1]=='\n') && (a[i]>='a'&&a[i]<='z'))
                a[i]=a[i]-32;
        printf("%s\n",a);
    }
}

发表于 2020-04-27 18:01:05 回复(0)
使用getchar()来获取输入    这样可以不吞掉空格 
然后对第一个字符进行判断是否是小写字母 然后根据其类型进行对应的变化或不改变  
然后对其他的字符  检测其前一个字符是否是空格  换行等题目给出的符号 
对前一个字符符合上述字符的  对该字符先进行判断是否是小写 
然后在对小写字母进行大写转换    ch[i]=ch[i]-32
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main(void)
{
    char ch[100];
    int i,j,n;
    i=0;
    while(ch[i]=getchar())
    {
        if(ch[i]=='\n') break;
        i++;
    }
    if(ch[0]>='a'&&ch[0]<='z')
        ch[0]=ch[0]-32;

    for(j=1;j<i;j++)
    {
        if(ch[j-1]==' '|| ch[j-1]=='\t'|| ch[j-1]=='\r'|| ch[j-1]=='\n')
        {
            if(ch[j]>='a'&&ch[j]<='z')
                ch[j]=ch[j]-32;
        }
    }
    for(j=0;j<i;j++)
        printf("%c",ch[j]);
    return 0;
}
发表于 2019-11-18 22:18:24 回复(0)
#include <cstdio>
#include <iostream>
using namespace std;
int main(){
    string s;
    while(getline(cin,s)){
        if(s[0]!=' '&&s[0]>='a'&&s[0]<='z')
            s[0] -= 32;
        for(int i = 1;i < s.length();i++){
            if((s[i-1] == ' '||s[i-1] == '\t')&&s[i]>='a'&&s[i]<='z')
                s[i] -= 32;
        }
        cout<<s<<endl;
    }
    
    return 0;
}

发表于 2019-03-01 11:25:51 回复(0)
这题也算比较简单?主要是空白符的处理问题,然后注意第二个if中空白符的或要和后面的'a'<=ch[i]<='z'取并才能满足条件,就是取条件的时候得要注意一下细节
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int main(){
    char ch[100];
    string str;
    while(getline(cin,str)){
        strcpy(ch,str.c_str());
        for(int i=0;i<strlen(ch);i++){
            if(i==0&&ch[i]>='a'&&ch[i]<='z')
                ch[i]='A'+ch[i]-'a';
            if((ch[i-1]=='\t'||ch[i-1]==' '||ch[i-1]=='\r'||ch[i-1]=='\n')
              &&ch[i]>='a'&&ch[i]<='z')
                ch[i]='A'+ch[i]-'a';
        }
        for(int i=0;i<strlen(ch);i++)
            cout<<ch[i];
        cout<<endl;
    }
}

发表于 2019-02-08 21:02:01 回复(1)
while True:
    try:
        string = list(input())
        lastBlank = True
        for i in range(len(string)):
            if string[i].isalpha() and lastBlank:
                string[i] = string[i].upper()
                lastBlank = False
            elif string[i] == " " or string[i] ==  "\t" or string[i] == "\r" or string[i] == '\n':
                lastBlank = True
            else:
                lastBlank = False
        print("".join(string))
    except Exception:
        break
编辑于 2018-10-02 23:52:20 回复(0)
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
    string ss;
    while(getline(cin,ss))
    {
        bool flag=true;
        for(int i=0;i<ss.length();i++)
        {
            if(flag)
            {
                ss[i]=toupper(ss[i]);
                flag=false;
            }
            if(ss[i]==' '||ss[i]=='\t'||ss[i]=='\n'||ss[i]=='\r')
                flag=true;
        }
        cout<<ss<<endl;
    }
    return 0;
}

发表于 2018-09-05 16:54:49 回复(1)
链接:https://www.nowcoder.com/questionTerminal/91f9c70e7b6f4c0ab23744055632467a 来源:牛客网
#include<iostream>
 #include<cstring>
 using namespace std;
 int main()
 {
     char s[100];
     int len,i;
     while(gets(s))
     {
         len=strlen(s);
         for(i=0;i<len;i++)
         {
             if(s[i]>='a'&&s[i]<='z')
             {
                 if(i==0||s[i-1]==' '||s[i-1]=='\t')
                     s[i]-=32;
             }
             cout<<s[i];
         }
         cout<<endl;
     }
     return 0;
 }

发表于 2018-02-22 12:48:18 回复(0)
#include<iostream>
using namespace std;
#include<string>

int main(){
    string s;
    while(getline(cin,s)){
        for(int i=0;i<s.size();i++){
            if(s[i]<='z' && s[i]>='a')
            	s[i]+='A'-'a';
            while(s[i] != ' ' && s[i] != '\t' && s[i] != '\r' && s[i] != '\n')
                i++;
        }
        cout<<s<<endl;
    }
}

发表于 2017-07-06 16:05:09 回复(0)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cctype>        // 用于判断字符类型
using namespace std;

const int maxn = 102;

char ch[maxn] = {0};

int main()
{
    int flag = 0;       // 是否是字母开头
    while(gets(ch))
    {
        flag = 0;
        for(int i = 0; i < strlen(ch); ++i)
        {
            if(islower(ch[i]) && flag == 0)
            {
                putchar(toupper(ch[i]));
                flag = 1;
            }
            else if(!isspace(ch[i]))
            {
                // 如果不是首字母且不是空白制表符则输出
                putchar(ch[i]);
                flag = 1;
            }
            else
            {
                putchar(ch[i]);
                flag = 0;
            }
        }
        cout << endl;
    }

    return 0;
}


发表于 2016-08-09 15:06:40 回复(0)
#include<iostream>
#include<string>
using namespace std;
int main(){
    string s;
    getline(cin,s);
    for(int i=0;i<s.length();i++){
        if(i==0)
            s[i]=toupper(s[i]);
        else{
            if(s[i-1]==' '||s[i-1]=='\t'||s[i-1]=='\r'||s[i-1]=='\n')
                s[i]=toupper(s[i]);
        }
    }
    cout<<s;
}

发表于 2019-03-08 13:55:55 回复(5)
#include <cstring>
#include <cstdio>
using namespace std;

int main()
{
    //freopen("date.txt", "r", stdin);
    char str[200] = " ";//初始化为含有一个空格的字符串,而不是空字符串
    while(gets(str + 1) != NULL){
        for(int i = 1; i < strlen(str); i++)
            if((str[i-1] == ' ' || str[i-1] == '\t') && str[i] >= 'a' && str[i] <= 'z')
                str[i] -= 32;
        
        for(int i = 1; i < strlen(str); i++)
            printf("%c", str[i]);
        printf("\n");
    }
    return 0;
}

编辑于 2018-02-13 10:53:23 回复(1)
#include<bits/stdc++.h>
char a[100];
int main(){
    while(gets(a)){
        int l=strlen(a);
        for(int i=0;i<l;i++)//注意分隔符不仅仅是空格
            if((i==0 ||a[i-1]==' '||a[i-1]=='\t'||a[i-1]=='\r'||a[i-1]=='\n') && a[i]>='a' && a[i]<='z')
                a[i]=a[i]-'a'+'A';
        puts(a);
    }
}
编辑于 2019-03-14 16:44:38 回复(2)
#include<stdio.h>
#include<string.h>
int main(){
    char a[1000];
    int len;
    while(gets(a)){
        len=strlen(a);
        if('a'<=a[0]&&a[0]<='z')
        a[0]=a[0]-'a'+'A';
        for(int i=0;i<len;i++){
            if(a[i]==' '||a[i]=='\t'||a[i]=='\r'||a[i]=='\n')
                if('a'<=a[i+1]&&a[i+1]<='z')
                a[i+1]=a[i+1]-'a'+'A';
        }
        for(int i=0;i<len;i++)
            printf("%c",a[i]);
        printf("\n");
    }
    return 0;
}

发表于 2019-03-14 21:10:19 回复(0)
#include<iostream>
(720)#include<sstream>
#include<algorithm>
(831)#include<queue>
#include<cmath>
(808)#include<string>
#include<cstdio>
(802)#include<regex>

using namespace std;


int main()                   
{
	string s;
	while (getline(cin, s))
	{

		if (s.size() > 1)
		{
			if (s[0] >= 'a'&&s[0] <= 'z' )s[0]=toupper(s[0]);
			for (int i = 1; i < s.size(); i++)
			{
				if (s[i] >= 'a'&&s[0] <= 'z' && (s[i - 1] == ' ' || s[i - 1] == '\t' || s[i - 1] == '\n' || s[i - 1] == '\r'))  s[i]=toupper(s[i]);
			}
		}
		else
			s[0]=toupper(s[0]);
	
		cout << s<<endl;
	}
	
}

发表于 2020-03-11 16:39:03 回复(1)
用getline(cin,str)读入一行。用空白符分割单词,判断是否为单词的首字母

#include <iostream>
#include <string>
using namespace std;

int main(){
    string str;
    while(getline(cin,str)){
        //首字母小写转大写
        if(str[0]>='a' && str[0]<='z')  str[0] = str[0]- 32;
        cout<<str[0];
        //保持空白符不变
        for(int i = 1; i < str.size(); i++){
            if(str[i]==' ' || str[i]=='\t' || str[i]=='\r' || str[i]=='\n' ){
                if(str[i+1]>='a' && str[i+1]<='z'){
                    str[i+1] -= 32; //空白符后的单词首字母大写
                } 
            }
            cout<<str[i];
        }
    }
    return 0;
}


编辑于 2024-02-13 15:17:02 回复(0)
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
	string str1;
	getline(cin, str1);
	int time = 1;
	for (int i = 0; i < str1.size(); i++) {
		if (time == 1) {
			if (str1[i] >= 'a' && str1[i] <= 'z') {
				str1[i] -= 32;
				time = 0;
			}
			else 
				time = 0;
		}
		if (str1[i] == ' '||str1[i]=='\t'||str1[i]=='\r'||str1[i]=='\n') time++;
	}
	cout << str1;

	return 0;
}

发表于 2023-01-30 18:54:08 回复(0)

问题信息

难度:
129条回答 12704浏览

热门推荐

通过挑战的用户

查看代码