2013-03-09 109 views
0

我知道这个问题已经被问到死,但我曾尝试分别给予this question和所有的解决方案,我的if语句仍然不执行.. 我的代码是这样的:字符串比较方案不工作

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

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

任何建议将不胜感激。

+2

我没有看到与此代码的任何问题。尝试在循环中打印数组的元素。同时检查伪造的空白字符。 – 2013-03-09 01:52:35

+0

也许你的输入字符串不是*你正在使用的样本。考虑到有些字符是不可打印的(所以你通常不会在你的编辑器或控制台中看到它们) – Raffaele 2013-03-09 01:56:53

+3

你发布的代码适合我。发布您用于测试代码的实际SSCCE。 – camickr 2013-03-09 01:57:46

回答

2

可正常工作确实

for (String token : "Something*like*this*".split("\\*")) { 
    if (token.equals("this")) { 
     System.out.println("Found this"); 
    } 
} 
+0

有趣的是,它不起作用,并通过解决您的解决方案,我已经得出结论,有什么地方我得到我的“东西*像* this”的问题(我不创建它),即使输出时看起来不错。我认为重组将会解决我的问题。谢谢 – Johnzo 2013-03-09 02:17:14

0

if执行在这里。

在drJava交互窗格(或您最喜欢的IDE窗格)中测试这个单独的部分(以检查它们的每个工作)。

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 
>