Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace string in java?

Tags:

java

string

regex

I have a String str = "a_bcde_fghij_k".

and I want to change it to "aBcdeFghijK"

If have a _ character, the next character will be change to uppercase and remove _ character.

How can I do this?

like image 745
furyfish Avatar asked Feb 27 '26 07:02

furyfish


1 Answers

I suspect you'll need to just go through this character by character, building up the string as you go. For example:

public static String underscoreToCapital(String text) {
    // This will be a bit bigger than necessary, but that shouldn't matter.
    StringBuilder builder = new StringBuilder(text.length());
    boolean capitalizeNext = false;
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c == '_') {
            capitalizeNext = true;
        } else {
            builder.append(capitalizeNext ? Character.toUpperCase(c) : c);
            capitalizeNext = false;
        }
    }
    return builder.toString();
}
like image 145
Jon Skeet Avatar answered Feb 28 '26 21:02

Jon Skeet