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

后端 未结 30 1767
情深已故
情深已故 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: 

提交回复
热议问题