0

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;
}
Pratik
  • 944
  • 4
  • 20

6 Answers6

1

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

P.S. 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

singhakash
  • 7,891
  • 6
  • 31
  • 65
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
1

Use replaceAll method

public static String filter(String X, String Y) {
    return X.replaceAll(Y,"");
}
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
1

I guess this will work for you :

if((x !=null && y !=null) && x.contains(y)) {
   System.out.println(x.replaceAll(y, ""));
}
Balaji
  • 1,009
  • 7
  • 21
0

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.

  • I added the extra check and it still errors out, do you have any other suggestions? – Nate Helfenberger Apr 06 '15 at 06:35
  • Can you please share the sample input that is used for your testing. Below is the code snippet. `public static String filter(String X, String Y) { String i = X; if ((X != null) && (X.length() >0) && (Y != null) &&Y.length() >0 && (i !=null) && (X.length() > Y.length())) { int z = X.indexOf(Y); i = X.substring(0, z) +X.substring(z + Y.length()); } return i; }` – Raghava Rudrakanth P V Apr 06 '15 at 06:52
0

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,"");

TheCurious
  • 593
  • 1
  • 4
  • 29
-1

You can use this:

String subString = testString.subString(firstIndex, secondIndex);

and you can get the index by this:

int index = testString.indexOf(String);
RJB
  • 32
  • 8