【问题标题】:"in" and "not in" in Java [duplicate]Java中的“in”和“not in”[重复]
【发布时间】:2016-05-01 11:00:17
【问题描述】:

我是 java 新手,我想知道是否有一种方法可以检查一个字符串与另一个字符串,我已经在 Python 中像这样完成了它”

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

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

编辑: 我以 String 为例,我主要是在寻找类似 python 的功能,正如我在标题中提到的 "in" 和 "not in" in java ,比较其他变量中存在的任何变量。

在 python 中,我可以比较 array 或 list 与单个 String 变量:

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

甚至 array 与 array:

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

单整数 vs 数组:

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

我主要是在寻找java提供的函数,它可以加快变量比较。

【问题讨论】:

  • 你检查过String类的Javadoc吗?
  • @Eran 不,我没有检查 String 类,因为在 python 中有“in”和“not in”来比较 任何值(不仅是字符串),它甚至可以检查数组、数字等...

标签: java python-2.7


【解决方案1】:

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");
}

【讨论】:

  • 我在上面添加了一些替代方案,这些替代方案可以在其他(更复杂的)用例中使用。
  • 感谢您的回复,这很有帮助,但我主要是在寻找内置于 java 中的函数来比较不同类型的变量,例如 python 如何处理“in”和“not in”,因为我请注意,由于在 java 中我们已经定义了与 python 不同的变量,因此比较变量应该更快更容易。
【解决方案2】:

有:

boolean isInString = fullString.contains(subString);

更新新问题:

如果你想检查字符串是否在给定的数组中,你有 Arrays 类:

Arrays.asList(givenArrayOfStrings).contains(yourString)

注意:对于您创建的特定对象,您必须实现方法 equals() 才能使用它。

【讨论】:

    【解决方案3】:

    在 java 中你至少可以有两种方法来做到这一点:

    public static void main(String[] args) {
        String text = "Tree";
    
        // option 1: index of... returns -1 if not present
        System.out.println(text.indexOf("re"));
    
        // option 2: contains
        System.out.println(text.contains("re"));
    }
    

    【讨论】:

      【解决方案4】:

      在java中的简单方法如下

      class StringTest { // Class
          public static void main(String[] args) { // Main method
              String text = "Tree";
              if (text.contains("re")) { // Checking
                  System.out.println("yes, there is re exist in Tree");
              }
          }
      }
      

      【讨论】:

        【解决方案5】:

        您可以使用String 类的contains() 方法简单地检查这一点。

        String s = "answer";
        if(s.contains("ans")) {
            System.out.print("Yes");
        }
        

        【讨论】:

          猜你喜欢
          • 2011-03-29
          • 2017-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-15
          • 2011-03-04
          相关资源
          最近更新 更多