Home > front end >  how I can do a replacement to an element in specific index without replace all the same elements in
how I can do a replacement to an element in specific index without replace all the same elements in

Time:09-07

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 ?!

CodePudding user response:

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"

CodePudding user response:

Unfortunately (idk why) there is no replaceLast in java.lang.String, but there is a replaceFirst(String regex, String replacement) function.

And at least:

  1. lastIndexOf
  2. "Substringing"
  3. Replacing (all or last) and .
  4. Joining back

Is a workaround. In code:

/**
* TODO hahaha
* @throws NullPointerException!
**/
private static String replaceLast(String in, char oldChar, char newChar) {
  int mem = in.lastIndexOf(oldChar); // 1.

  return mem > -1 ? 
    in.substring(0, mem) // 2.(a)
    .concat( // 4. ;)
      in.substring(mem) // 2.(b)
      .replace(oldChar, newChar) // 3.
    ) : 
  in;
}

Apache's StringUtil is more powerful, also has no "replace last" function ;(, but at least a "reverse"( replace) functions.

When is an option, see Bohemian's answer!

  • Related