在java中拆分字符串给出一些问题

时间:2014-03-10 06:04:54

标签: java split

public class llearning1 {

    public static void main(String[] args) {

        String text = "is";
        String x = "what is good";
        String y[] = x.split(" ");

        for (String temp: y) {

            if (temp == text) {
                System.out.println("found");
            } else {
                System.out.println("nothing");
            }
        }
    }
}

输出:

预期:代码应显示“找到”

但它显示“没有”

2 个答案:

答案 0 :(得分:1)

使用equals()方法将字符串与==运算符

进行比较

==运算符用于比较对象的引用。

将我f (temp == text)更改为if (temp.equals(text))

答案 1 :(得分:0)

String是使用.equals()方法进行对象和对象相等性检查。

所以试试:

if(temp.equals(text))

== 运算符用于对象引用比较意味着两个引用指向同一个对象或不指向或原始(int,double,...)值比较。