Regex replace space and word with FirstUpper words

I tried to use regex to change the next line

String input = "Creation of book orders" 

to

String output = "CreationOfBookOrders"

I tried the following, waiting to replace a word and a word with a word.

input.replaceAll("\\s\\w", "(\\w)");
input.replaceAll("\\s\\w", "\\w");

but here the string replaces the space and the word with the character 'w' instead of the word.

I can not use any WordUtilsor StringUtilsor such Util classes. Else I could replace all spaces with an empty string and apply WordUtils.capitalizeor similar methods.

How else (preferably using regex) I can get higher outputfrom input.

+4
source share
1 answer

, String.replaceAll. , , - , .

javadoc Matcher.replaceAll , .

. :

StringBuilder sb = new StringBuilder(input);
Pattern pattern = Pattern.compile("\\s\\w");
Matcher matcher = pattern.matcher(s);
int pos = 0;
while (matcher.find(pos)) {
    String replacement = matcher.group().substring(1).toUpperCase();
    pos = matcher.start();
    sb.replace(pos, pos + 2, replacement);
    pos += 1;
}
output = sb.toString();

( , .)

+2

All Articles