How to capitalize the first letter of word in a string using Java?

前端 未结 25 1553
抹茶落季
抹茶落季 2020-11-27 09:50

Example strings

one thousand only
two hundred
twenty
seven

How do I change the first character of a string in capital letter and not change

25条回答
  •  一个人的身影
    2020-11-27 10:31

    Here you go (hope this give you the idea):

    /*************************************************************************
     *  Compilation:  javac Capitalize.java
     *  Execution:    java Capitalize < input.txt
     * 
     *  Read in a sequence of words from standard input and capitalize each
     *  one (make first letter uppercase; make rest lowercase).
     *
     *  % java Capitalize
     *  now is the time for all good 
     *  Now Is The Time For All Good 
     *  to be or not to be that is the question
     *  To Be Or Not To Be That Is The Question 
     *
     *  Remark: replace sequence of whitespace with a single space.
     *
     *************************************************************************/
    
    public class Capitalize {
    
        public static String capitalize(String s) {
            if (s.length() == 0) return s;
            return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
        }
    
        public static void main(String[] args) {
            while (!StdIn.isEmpty()) {
                String line = StdIn.readLine();
                String[] words = line.split("\\s");
                for (String s : words) {
                    StdOut.print(capitalize(s) + " ");
                }
                StdOut.println();
            }
        }
    
    }
    

提交回复
热议问题