Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String index out of range with replace all

Tags:

java

replace

How can I replace mapDir surrounded by <> to a certain string?

  String mapDir = "D:\\mapping\\specialists\\ts_gpc\\";
  String test = "foo: <mapDir> -bar";
  println(test.replaceAll("<mapDir>", mapDir));

The above gives me a StringIndexOutOfBoundsException.

This code below for me, but I think pure java has to work as well.

static String replaceWord(String original, String find, String replacement) {
    int i = original.indexOf(find);
    if (i < 0) {
        return original;  // return original if 'find' is not in it.
    }

    String partBefore = original.substring(0, i);
    String partAfter  = original.substring(i + find.length());

    return partBefore + replacement + partAfter;
}
like image 533
clankill3r Avatar asked Dec 09 '25 05:12

clankill3r


1 Answers

You dont need replaceAll method as you are not using regex. Instead you could work with replace api like below:

String mapDir = "D:\\mapping\\specialists\\ts_gpc\\";
String test = "foo: <mapDir> -bar";
System.out.println(test.replace("<mapDir>", mapDir));
like image 56
SMA Avatar answered Dec 10 '25 19:12

SMA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!