7

Suppose I want to change a lowercase string to "title case"; where the first letter of every word is capitalized. Can this be done using a single call to replaceAll() by using a modifier in the replacement expression?

For example,

str = str.replaceAll("\\b(\\S)", "???$1");

Where "???" is some expression that folds the case of the next letter.

I have seen this is other tools (like textpad), where \U will fold the next letter to uppercase.

?

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    This isn't available in Java unfortunately. You will have to run a loop and replace the matches one by one. See [this answer](http://stackoverflow.com/a/2770977/1343161). – Keppil Dec 19 '13 at 05:51
  • 1
    If you're not averse to using Apache Commons, then you can use `org.apache.commons.lang3.StringUtils` like so: `StringUtils.capitalize(str.toLowerCase())`. This can not be done with standard Java libraries however. – Taylor Hx Dec 19 '13 at 05:56
  • Maybe look at [WordUtils](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/WordUtils.html). – devnull Dec 19 '13 at 05:57
  • Maybe you could just use a [callback of your own](http://stackoverflow.com/questions/375420/java-equivalent-to-phps-preg-replace-callback) ? – HamZa Dec 19 '13 at 08:23

1 Answers1

2

Not possible with replaceAll. But you can use regex and split:

public String titleTextConversion(String text) {
    String[] words = text.split("(?<=\\W)|(?=\\W)");
    StringBuilder sb = new StringBuilder();
    for (String word : words) {
        if (word.length() > 0)
            sb.append(word.substring(0, 1).toUpperCase()).append(word.substring(1).toLowerCase());
    }
    return sb.toString();
}
Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51