[英]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? 有任何想法吗?
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.