The title of the first character after a blank space If the full sentence is upper case java

I have some problem how to make amends for the first word of a line if the whole sentence is uppercase. For example: "VESSEL ONE (L) INC" The result I want is: "Vessel One (L) Inc"

I am currently applying this code, but this only works if all the sentences are lowercase

String source = "vessel two management sdn bhd";
StringBuffer res = new StringBuffer();

String[] strArr = source.split(" ");
 for (String str : strArr) {
  char[] stringArray = str.trim().toCharArray();
  stringArray[1] = Character.toLowerCase(stringArray[1]);
  str = new String(stringArray);

  res.append(str).append(" ");
  }

res.toString().trim()

Can anybody help me?

+4
source share
3 answers

First, please prefer StringBuildermore StringBuffer. Secondly, you can use WordUtils.capitalizeFully(String), for example

String source = "VESSEL ONE (L) INC";
String capitalized = WordUtils.capitalizeFully(source);

or (if you cannot use apache commons), you can write your own, for example

private static String capitalizeFully(String str) {
    StringBuilder sb = new StringBuilder();
    boolean cnl = true; // <-- capitalize next letter.
    for (char c : str.toCharArray()) {
        if (cnl && Character.isLetter(c)) {
            sb.append(Character.toUpperCase(c));
            cnl = false;
        } else {
            sb.append(Character.toLowerCase(c));
        }
        if (Character.isWhitespace(c)) {
            cnl = true;
        }
    }
    return sb.toString();
}

public static void main(String[] args) {
    String source = "VESSEL ONE (L) INC";
    System.out.println(capitalizeFully(source));
}
+3

WordUtils, lib. .

toLowerCase .

+2

try it

    StringBuffer sb = new StringBuffer();
    Matcher m = Pattern.compile("\\b.+?\\b").matcher(source);
    while(m.find()) {
        String s = m.group().substring(0,1).toUpperCase() + m.group().substring(1).toLowerCase();
        m.appendReplacement(sb, s);
    }
    String res = sb.toString();
0
source

All Articles