Java – string index using replace all is out of range
•
Java
How to 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 a string index out of boundary exception
The following code is for me, but I think pure Java must also work properly
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;
}
Solution
You don't need the replaceall method because you don't use regular expressions Instead, you can use the following alternative API:
String mapDir = "D:\\mapping\\specialists\\ts_gpc\\";
String test = "foo: <mapDir> -bar";
System.out.println(test.replace("<mapDir>",mapDir));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
