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

前端 未结 25 1081
抹茶落季
抹茶落季 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:28

    Even for "simple" code, I would use libraries. The thing is not the code per se, but the already existing test cases covering exceptional cases. This could be null, empty strings, strings in other languages.

    The word manipulation part has been moved out ouf Apache Commons Lang. It is now placed in Apache Commons Text. Get it via https://search.maven.org/artifact/org.apache.commons/commons-text.

    You can use WordUtils.capitalize(String str) from Apache Commons Text. It is more powerful than you asked for. It can also capitalize fulle (e.g., fixing "oNe tousand only").

    Since it works on complete text, one has to tell it to capitalize only the first word.

    WordUtils.capitalize("one thousand only", new char[0]);
    

    Full JUnit class to enable playing with the functionality:

    package io.github.koppor;
    
    import org.apache.commons.text.WordUtils;
    import org.junit.jupiter.api.Test;
    
    import static org.junit.jupiter.api.Assertions.*;
    
    class AppTest {
    
      @Test
      void test() {
        assertEquals("One thousand only", WordUtils.capitalize("one thousand only", new char[0]));
      }
    
    }
    
    0 讨论(0)
  • 2020-11-27 10:29

    Also, There is org.springframework.util.StringUtils in Spring Framework:

    StringUtils.capitalize(str);
    
    0 讨论(0)
  • 2020-11-27 10:30
    String sentence = "ToDAY   WeAthEr   GREat";    
    public static String upperCaseWords(String sentence) {
            String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
            String newSentence = "";
            for (String word : words) {
                for (int i = 0; i < word.length(); i++)
                    newSentence = newSentence + ((i == 0) ? word.substring(i, i + 1).toUpperCase(): 
                        (i != word.length() - 1) ? word.substring(i, i + 1).toLowerCase() : word.substring(i, i + 1).toLowerCase().toLowerCase() + " ");
            }
    
            return newSentence;
        }
    //Today Weather Great
    
    0 讨论(0)
  • 2020-11-27 10:30

    Adding everything together, it is a good idea to trim for extra white space at beginning of string. Otherwise, .substring(0,1).toUpperCase will try to capitalize a white space.

        public String capitalizeFirstLetter(String original) {
            if (original == null || original.length() == 0) {
                return original;
            }
            return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
        }
    
    0 讨论(0)
  • 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();
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-11-27 10:35

    I would like to add a NULL check and IndexOutOfBoundsException on the accepted answer.

    String output = input.substring(0, 1).toUpperCase() + input.substring(1);
    

    Java Code:

      class Main {
          public static void main(String[] args) {
            System.out.println("Capitalize first letter ");
            System.out.println("Normal  check #1      : ["+ captializeFirstLetter("one thousand only")+"]");
            System.out.println("Normal  check #2      : ["+ captializeFirstLetter("two hundred")+"]");
            System.out.println("Normal  check #3      : ["+ captializeFirstLetter("twenty")+"]");
            System.out.println("Normal  check #4      : ["+ captializeFirstLetter("seven")+"]");
    
            System.out.println("Single letter check   : ["+captializeFirstLetter("a")+"]");
            System.out.println("IndexOutOfBound check : ["+ captializeFirstLetter("")+"]");
            System.out.println("Null Check            : ["+ captializeFirstLetter(null)+"]");
          }
    
          static String captializeFirstLetter(String input){
                 if(input!=null && input.length() >0){
                    input = input.substring(0, 1).toUpperCase() + input.substring(1);
                }
                return input;
            }
        }
    

    Output:

    Normal  check #1      : [One thousand only]
    Normal  check #2      : [Two hundred]
    Normal  check #3      : [Twenty]
    Normal  check #4      : [Seven]
    Single letter check   : [A]
    IndexOutOfBound check : []
    Null Check            : [null]
    
    0 讨论(0)
提交回复
热议问题