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

后端 未结 30 1768
情深已故
情深已故 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: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);
    }
    

提交回复
热议问题