Yukera
Yukera

Reputation: 71

toUpperCase at specific index uppercases more chars than supposed to

I'm trying to solve a problem that takes specific symbols and removes them from the string, then it converts the character following that symbol to uppercase. But for some reason characters after the uppercased characters are also getting uppercased.

s is the given string.

String[] symbols = { "-", "_" };
int index = 0;   

for(String symbol : symbols) {
  while(s.indexOf(symbol) >= 0){
    index = s.indexOf(symbol);
    s = s.replaceFirst(symbol, "");
    s = s.replace(s.charAt(index), Character.toUpperCase(s.charAt(index)));
    System.out.println(index);
  }
}

The given input is: river_Green_Green_Wall_Lake_left_Samurai_Wall

What I expected was: riverGreenGreenWallLakeLeftSamuraiWall

But what I got instead is: riverGreenGreenWaLLLakeLeftSamuraiWaLL

Upvotes: 1

Views: 679

Answers (2)

becher henchiri
becher henchiri

Reputation: 667

just you need call replace method in the same line when you replace symbol:

    String s ="river_Green_Green_Wall_Lake_left_Samurai_Wall";
    String[] symbols = { "-", "_" };
    int index = 0;

  for(String symbol : symbols) {
     while(s.indexOf(symbol) >= 0){
       index = s.indexOf(symbol);
       s = s.replaceFirst(symbol, "").replace(s.charAt(index) ,Character.toUpperCase(s.charAt(index)));
      }
    }
    System.out.println(s);
}

Upvotes: 1

Tom Chumley
Tom Chumley

Reputation: 144

rather than using replace, you should try rebuilding the string with the index uppercased

    for(String symbol : symbols) {
      while(s.indexOf(symbol) >= 0){
        index = s.indexOf(symbol);
        //
        s = s.substring(0,index)+s.substring(index+1,index+2).toUpperCase()+s.substring(index+2);
        //
        System.out.println(s);
      }
    }

Upvotes: 1

Related Questions