0

I have this:

private String remove_spaces(String s){
    s = s.trim();
    String updated = "";
    for (int i = 0;  i < s.length(); i++) {
        String tester = s.substring(i, i + 1);
        String space = " ";
        boolean isSpace = tester.equals(space);
        if (isSpace = false)
            updated += tester;
    }
    return updated;
}

And it throws an StringIndexOutOfBounds, and I don't understand why. Why?

hata
  • 11,633
  • 6
  • 46
  • 69

3 Answers3

0

You need == to do comparison while = is substitution operator.

if (isSpace == false)

Additionally, you can use !(=not) to shorten your code like below:

private String remove_spaces(String s) {
    s = s.trim();
    String updated = "";
    for (int i = 0;  i < s.length(); i++) {
        String tester = s.substring(i, i + 1);
        if (!tester.equals(" ")) {
            updated += tester;
        }
    }
    return updated;
}
hata
  • 11,633
  • 6
  • 46
  • 69
0

You've got index out of bounds error because you are trying to reach an index greater than the actual length of your array

String tester = s.substring(i,i + 1);

I suggest an if clause like this

private String remove_spaces(String s) {
    s = s.trim();
    String updated = "";
    String tester = "";
    for (int i = 0;  i < s.length(); i++) {
        if (i != s.length-1) {
            tester = s.substring(i, i + 1);
        }else{
            tester = s.substring(i);
        }
        if (!tester.equals(" ")) {
            updated += tester;
        }
    }
    return updated;
}

alejandro00
  • 144
  • 6
0

The better way to remove spaces in your String in Java would be

str = str.replace(" ","");

But if you want something similar to your code, try the below one, I guess substring is not needed we can use charAt for that.

private static String remove_spaces(String s) {
    s = s.trim();
    StringBuilder updated = new StringBuilder();
    for (int i = 0;  i < s.length(); i++) {
      Character tester = s.charAt(i);
      if (!tester.equals(' ')) {
        updated.append(tester);
      }
    }
    return updated.toString();
  }