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.

5
  • 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. Commented Mar 9, 2013 at 1: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) Commented Mar 9, 2013 at 1:56
  • 3
    Your posted code works fine for me. Post the actual SSCCE you used to test the code. Commented Mar 9, 2013 at 1:57
  • It works as expected. What is your environment? java version etc. Are you using threading ? Commented Mar 9, 2013 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 Commented Mar 10, 2013 at 1:54

2 Answers 2

2

This works as expected indeed

for (String token : "Something*like*this*".split("\\*")) { if (token.equals("this")) { System.out.println("Found this"); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

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 "Somethinglikethis" from (I don't create it) even though it looks fine when outputted. I think restructuring that will solve my problem. Thank you
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 > 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.