0

I know this question has been asked to death but I have tried all solutions that were given to this question and my if statement still doesn't execute.. My code goes like this:

String s = "Something*like*this*";
String[] sarray = s.split("\\*");

for(int i = 0; i < sarray.length; i++) {
  if(sarray[i].equals("this")) {
    //do something
  }
}

Any suggestions would be greatly appreciated.

Community
  • 1
  • 1
Johnzo
  • 112
  • 10
  • 2
    I don't see any problems with this code. Try printing out the elements of the array in your loop. Also check for spurious whitespace characters. – Code-Apprentice Mar 09 '13 at 01:52
  • Maybe your input string is not *exactly* the one you use in this sample. Consider there are characters that are not printable (so you don't usually see them neither in your editor, nor in the console) – Raffaele Mar 09 '13 at 01:56
  • 3
    Your posted code works fine for me. Post the actual SSCCE you used to test the code. – camickr Mar 09 '13 at 01:57
  • It works as expected. What is your environment? java version etc. Are you using threading ? – Rajender Saini Mar 09 '13 at 21:45
  • I'm using eclipse. The problem was with the way I store and retrieve s from permanent storage on the android device. I changed to sql database and it all works. Thanks for your comments – Johnzo Mar 10 '13 at 01:54

2 Answers2

2

This works as expected indeed

for (String token : "Something*like*this*".split("\\*")) {
    if (token.equals("this")) {
        System.out.println("Found this");
    }
}
Raffaele
  • 20,627
  • 6
  • 47
  • 86
  • Interesting, unfortunately it hasn't worked and by messing around with your solution, I've concluded that there is a problem with where I get my "Something*like*this" from (I don't create it) even though it looks fine when outputted. I think restructuring that will solve my problem. Thank you – Johnzo Mar 09 '13 at 02:17
0

The if will execute here.

Test this in drJava interactions pane(or your fav IDE pane), the individual pieces(to check they each work).

Welcome to DrJava.  Working directory is C:\JavaProjects
> String s = "Something*like*this";

> String[] sarray = s.split("\\*");

> sarray[0]

"Something"

> sarray[1]

"like"

> sarray[2]

"this"

> sarray[3]

java.lang.ArrayIndexOutOfBoundsException

> sarray.length

> 3 

> sarray[1].equals("this")

false
> 
Caffeinated
  • 11,982
  • 40
  • 122
  • 216