I wan't to remove Y from X and this compiles, however when I run it in my main method I get an error saying out of bounds. I am unsure what is wrong. any help would be appreciated.
public static String filter(String X, String Y) {
String i = X;
if ((X != null) && (X.length() >0) && (Y != null) &&Y.length() >0 && (i !=null)){
int z = X.indexOf(Y);
i = X.substring(0, z) +X.substring(z + Y.length());
}
return i;
}
As @singhakash already pointed out that
int z = X.indexOf(Y); --> this is returning -1
So
X.substring(0, z)
become
X.substring(0, -1)
causing OutOfBounds Exception
PS Why have you complicated it so much !! Instead you can use String#replace
or String#replaceAll
String X="StackOverflow";
String Y="flow";
X=X.replaceAll(Y,"");
System.out.println(X);
Output
StackOver
Demo1 - if y is not present in x you get index out of bound
Demo2 - if y is present in x you will get correct output
Use replaceAll method
public static String filter(String X, String Y) {
return X.replaceAll(Y,"");
}
I guess this will work for you :
if((x !=null && y !=null) && x.contains(y)) {
System.out.println(x.replaceAll(y, ""));
}
The Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
occurs when the length of string X is less than string Y because of this X.substring(z + Y.length())
Have a additional check for "X.length() > Y.length()" and it should work fine.
If You want to remove all occurrence of Y in X use the following code.
public static String filter(String X, String Y) {
if ((X != null) && (X.length() >0) && (Y != null) &&Y.length() >0) {
while(X.contains(Y)){
int z = X.indexOf(Y);
X = X.substring(0, z) +X.substring(z + Y.length());
}}
return X;
also if X does not contain Y then int z = X.indexOf(Y);
--> this is returning -1 X.substring(0, z)
ie X.substring(0, -1)
-->causing OutOfBounds Exception
It is better to use X=X.replaceAll(Y,"");
You can use this:
String subString = testString.subString(firstIndex, secondIndex);
and you can get the index by this:
int index = testString.indexOf(String);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.