This question already has answers here:
How to search a string in another string? [duplicate]
                                
                                    (5个答案)
                                
                        
                3年前关闭。
            
        

我是Java的新手,我想知道是否有一种方法可以将一个字符串与另一个字符串进行检查,我已经在Python中做到了,就像这样”

text = "Tree"
if "re" in text:
    print "yes, there is re exist in Tree"


我们在Java中有这样一种方法来检查一个字符串是否存在于另一个字符串中吗?

编辑:我以String为例,我主要是在寻找类似python的函数,如我在标题中提到的Java中的“ in”和“ not in”中提到的那样,比较存在于另一个变量中的任何变量。

在python中,我可以比较数组或列表与单个String变量:

myList = ["Apple", "Tree"]
if "Apple" in myList:
    print "yes, Apple exist"


偶数组与数组:

myList = ["Apple", "Tree","Seed"]
if ["Apple","Seed"] in myList:
    print "yes, there is Apple and Seed in your list"


和单个Integer vs array:

myNumber = [10, 5, 3]
if 10 in myNumber:
    print "yes, There is 10"


我主要是在寻找Java提供的功能,以加快变量比较的速度。

最佳答案

String#contains是您要寻找的。

String text = "Tree";
if (text.contains("re")) {
    System.out.println("yes, there is re exist in Tree");
}


备择方案:

String#indexOf

String text = "Tree";
if (text.indexOf("re") != -1) {
    System.out.println("yes, there is re exist in Tree");
}


String#matches

String text = "Tree";
if (text.matches(".*re.*")) {
    System.out.println("yes, there is re exist in Tree");
}


Pattern

String text = "Tree";
if (Pattern.compile(".*re.*").matcher(text).find()) {
    System.out.println("yes, there is re exist in Tree");
}

09-10 03:38
查看更多