Loading

考研机试 57.首字母大写

 

时间:2021/03/08

 

一.题目描述

对一个字符串中的所有单词,如果单词的首字母不是大写字母,则把单词的首字母变成大写字母。 在字符串中,单词之间通过空白符分隔,空白符包括:空格(' ')、制表符('\t')、回车符('\r')、换行符('\n')。

输入描述

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

输出描述

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

题目链接

https://www.nowcoder.com/practice/91f9c70e7b6f4c0ab23744055632467a?

tpId=40&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey

 

二.算法

题解

虽然一个句子可能跨越多行,但是这里我们仍可以以行为单位分别进行处理。我们将读入的一行转化为字符数组,对于第一个字符,若其为小写字母则转化为大写,因为每一行的第一个字母前虽然没有空白符,但它认为单词首字母。这里要注意,即使第一个字母不是小写字母也要输出。然后我们对于之后的字符进行循环判断,若当前字符为空白字符,则判断后面一个字符是否为小写字母,若是则转化为大写字母,然后输出当前字符。

代码

import java.util.Scanner;

public class Main{
    
    public static void main(String[] args){
        
        Scanner in = new Scanner(System.in);
        
        while(in.hasNext()){
            
            //读取输入
            char[] ch = (in.nextLine()).toCharArray();
            
            //将首字母大写
            if(ch[0] >= 'a' && ch[0] <= 'z'){
                ch[0] -= 32;
            }
            System.out.print(ch[0]);
            for(int i = 1; i < ch.length; i++){
                if(ch[i] == ' ' || ch[i] == '\t' || ch[i] == '\r' || ch[i] == '\n'){
                    if(ch[i + 1] >= 'a' && ch[i + 1] <= 'z'){
                        ch[i + 1] -= 32;
                    }
                }
                System.out.print(ch[i]);
            }
            
            System.out.println();
        }
    }
}

 

posted @ 2021-03-08 17:47    阅读(88)  评论(0编辑  收藏  举报