Reputation: 93
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. Any ideas?
Upvotes: 3
Views: 223
Reputation: 9721
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));
Upvotes: 2
Reputation: 46428
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
}
}
Upvotes: 6
Reputation: 21
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
}
Upvotes: 2
Reputation: 1180
You can use Matcher and Pattern.compiler in the regex package. 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());
}
Upvotes: 0
Reputation: 138
I would split the list into string array and then using foreach loop i would find the match by comparing the values.
Upvotes: 2
Reputation: 2296
Array ints = listOfIntegers.split(' ');
print ints.inArray(integerToLookFor);
Upvotes: 0