包含无法正常工作的方法

时间:2014-01-08 11:16:15

标签: java

您能告诉我为什么下面的代码中包含不起作用:

String str=
        "/XYZ1/Test3-NV28"+
        "/678/13855497776650XB"+
        "/123/";

if ("XYZ".contains(str))

        System.out.println("yes");
else
    System.out.println("no");
    }

RP

6 个答案:

答案 0 :(得分:3)

您以错误的方式使用Yoda style condition。您必须将其用作

if (str.contains("XYZ")) {

}

进一步澄清

 String x= "test";
    if (x.contains("est")) {  //true
        System.out.println("true");
    }
 if(x.contains("set")){  //false
     System.out.println("false");
 }

答案 1 :(得分:0)

更改

if ("XYZ".contains(str))

if (str.contains("XYZ"))

答案 2 :(得分:0)

将此if ("XYZ".contains(str))更改为if (str.contains("XYZ"))

您正在搜索XYZ中是否存在String str

来自oracle docs

当且仅当此字符串包含指定的char值序列时,才返回true。

答案 3 :(得分:0)

应该是

str.contains("XYZ")

因为str包含"XYZ",但XYZ不包含str

包含方法名称本身就说明了方法的含义...

答案 4 :(得分:0)

更改此

if ("XYZ".contains(str))

if (str.contains("XYZ"))

因为str包含"XYZ"。而"XYZ"不包含str 这是Java Doc link

答案 5 :(得分:0)

如果我们有两个字符串,并且我们想要使用contains方法对它们进行比较,则包含的字符串必须是原始字符串的子集。 即

 String originalString="Africa is a continent";
    System.oout.println(originalString.contains("Africa"))
     ///true, will be printed because Africa is in 
                                 ///the originalString
       }
   System.out.println("Africa".contains(OriginalString))// it will print false 

    }
相关问题