How to capitalize the first character of each word in a string

后端 未结 30 1364
情深已故
情深已故 2020-11-22 02:08

Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?

Examples:

  • jon
相关标签:
30条回答
  • 2020-11-22 02:39

    I decided to add one more solution for capitalizing words in a string:

    • words are defined here as adjacent letter-or-digit characters;
    • surrogate pairs are provided as well;
    • the code has been optimized for performance; and
    • it is still compact.

    Function:

    public static String capitalize(String string) {
      final int sl = string.length();
      final StringBuilder sb = new StringBuilder(sl);
      boolean lod = false;
      for(int s = 0; s < sl; s++) {
        final int cp = string.codePointAt(s);
        sb.appendCodePoint(lod ? Character.toLowerCase(cp) : Character.toUpperCase(cp));
        lod = Character.isLetterOrDigit(cp);
        if(!Character.isBmpCodePoint(cp)) s++;
      }
      return sb.toString();
    }
    

    Example call:

    System.out.println(capitalize("An à la carte StRiNg. Surrogate pairs:                                                                     
    0 讨论(0)
  • 2020-11-22 02:39

    1. Java 8 Streams

    public static String capitalizeAll(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
    
        return Arrays.stream(str.split("\\s+"))
                .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
                .collect(Collectors.joining(" "));
    }
    

    Examples:

    System.out.println(capitalizeAll("jon skeet")); // Jon Skeet
    System.out.println(capitalizeAll("miles o'Brien")); // Miles O'Brien
    System.out.println(capitalizeAll("old mcdonald")); // Old Mcdonald
    System.out.println(capitalizeAll(null)); // null
    

    For foo bAR to Foo Bar, replace the map() method with the following:

    .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase())
    

    2. String.replaceAll() (Java 9+)

    ublic static String capitalizeAll(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
    
        return Pattern.compile("\\b(.)(.*?)\\b")
                .matcher(str)
                .replaceAll(match -> match.group(1).toUpperCase() + match.group(2));
    }
    

    Examples:

    System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java
    System.out.println(capitalizeAll("i am atta")); // I Am Atta
    System.out.println(capitalizeAll(null)); // null
    

    3. Apache Commons Text

    System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere
    System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky!
    System.out.println(WordUtils.capitalize(null)); // null
    

    For titlecase:

    System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar
    System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue!
    

    For details, checkout this tutorial.

    0 讨论(0)
  • 2020-11-22 02:39

    This is just another way of doing it:

    private String capitalize(String line)
    {
        StringTokenizer token =new StringTokenizer(line);
        String CapLine="";
        while(token.hasMoreTokens())
        {
            String tok = token.nextToken().toString();
            CapLine += Character.toUpperCase(tok.charAt(0))+ tok.substring(1)+" ";        
        }
        return CapLine.substring(0,CapLine.length()-1);
    }
    
    0 讨论(0)
  • 2020-11-22 02:40

    The following method converts all the letters into upper/lower case, depending on their position near a space or other special chars.

    public static String capitalizeString(String string) {
      char[] chars = string.toLowerCase().toCharArray();
      boolean found = false;
      for (int i = 0; i < chars.length; i++) {
        if (!found && Character.isLetter(chars[i])) {
          chars[i] = Character.toUpperCase(chars[i]);
          found = true;
        } else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
          found = false;
        }
      }
      return String.valueOf(chars);
    }
    
    0 讨论(0)
  • 2020-11-22 02:41

    Try this very simple way

    example givenString="ram is good boy"

    public static String toTitleCase(String givenString) {
        String[] arr = givenString.split(" ");
        StringBuffer sb = new StringBuffer();
    
        for (int i = 0; i < arr.length; i++) {
            sb.append(Character.toUpperCase(arr[i].charAt(0)))
                .append(arr[i].substring(1)).append(" ");
        }          
        return sb.toString().trim();
    }  
    

    Output will be: Ram Is Good Boy

    0 讨论(0)
  • 2020-11-22 02:41

    Using org.apache.commons.lang.StringUtils makes it very simple.

    capitalizeStr = StringUtils.capitalize(str);
    
    0 讨论(0)
提交回复
热议问题