简体   繁体   English

比较两个整数串并打印出匹配

[英]Comparing two strings of integers and printing out a match

Let's say these are my two strings 让我们说这是我的两个字符串

String listOfIntegers = ("1 5 9 12 15 50 80 121");
String integerToLookFor = ("12");

I want my program to scan listOfIntegers and print out if integerToLookFor is in the string. 我希望我的程序扫描listOfIntegers并打印出integerToLookFor是否在字符串中。 Any ideas? 有任何想法吗?

  1. Split the string with space as a delimiter to get an Array of Strings. 将带有空格的字符串拆分为分隔符以获取字符串数组。
  2. Scan the Array and check every element if it is equal to the lookup variable. 扫描数组并检查每个元素是否等于查找变量。

Code: 码:

String listOfIntegers = ("1 5 9 12 15 50 80 121");
String integerToLookFor = ("12");
String[] splitArr = listOfIntegers.split("\\s");
for(String s: splitArr){
    if(s.equals(integerToLookFor)) {
        System.out.println("found: " + s);
        break; //breaks out of the loop
    }
}

我将列表拆分为字符串数组,然后使用foreach循环,我将通过比较值找到匹配。

If you ensure that both the list and the number to search for are enclosed in spaces, you can simplify the search: 如果确保列表和要搜索的数字都包含在空格中,则可以简化搜索:

    String listOfIntegers = " " + "1 5 9 12 15 50 80 121" + " ";
    String integerToLookFor = " " + "12" + " ";
    if (listOfIntegers.indexOf(integerToLookFor) != -1) {
        // match found
    }
import java.util.Arrays;    
String listOfIntegers = ("1 5 9 12 15 50 80 121");
String integerToLookFor = ("12");    
System.out.println(Arrays.asList(listOfIntegers.split(" ")).contains(integerToLookFor));
Array ints = listOfIntegers.split(' ');
print ints.inArray(integerToLookFor);

You can use Matcher and Pattern.compiler in the regex package. 您可以在regex包中使用Matcher和Pattern.compiler。 See the example below: 请参阅以下示例:

Pattern p = Pattern.compile(integerToLookFor);
Matcher m = p.matcher(listOfIntegers);
while(m.find()){

   System.out.println("Starting Point:"+m.start()+"Ending point:"+m.end());

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM