1

how I can do a replacement to an element in specific index without replace all the same elements in other index as a string in java , like input a string "22" ,and you should make the last char be 0 , so if I did the built-in method , string.replace(oldchar,newchar) ,it'll replace the first 2 too , because I replaced a char to another , not index to another one ,so what the solution in java ?!

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • Does this answer your question? [Replace the last occurrence of a string in another string](https://stackoverflow.com/questions/23325800/replace-the-last-occurrence-of-a-string-in-another-string) – xerx593 Sep 06 '22 at 15:56

1 Answers1

1

Use a regex negative lookahead:

str = str.replaceAll("2(?!.*2)", "0");

Regex breakdown:

  • 2 a literal "2"
  • (?!.*2) a negative lookahead for a "2", which in English means "a 2 does not exist after this point in the input"
Bohemian
  • 412,405
  • 93
  • 575
  • 722