1

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

Kaan
  • 5,434
  • 3
  • 19
  • 41
Yukera
  • 71
  • 5
  • 4
    The method ```replace``` replaces all occurrences of the given string. This is not what you want. Since there is no ```replaceFirst``` with a starting index, you might need to use some ```substring``` calls in combination with it to achieve your goal. – Islingre Oct 17 '19 at 14:56
  • Possible duplicate of [Replace a character at a specific index in a string?](https://stackoverflow.com/questions/6952363/replace-a-character-at-a-specific-index-in-a-string) – Armali Oct 17 '19 at 15:11
  • Thank you @Islingre, using substring to capitalize worked! – Yukera Oct 17 '19 at 15:14

2 Answers2

1

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);
      }
    }
Tom Chumley
  • 144
  • 5
  • 3
    It would be better to do this with a `StringBuilder`, since this would avoid continually rebuilding and discarding the string: you can use `StringBuilder.indexOf` to find the character, and then `StringBuilder.set` to change it. – Andy Turner Oct 17 '19 at 15:10
1

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);
}
becher henchiri
  • 618
  • 4
  • 10