user1796741
user1796741

Reputation: 93

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. Any ideas?

Upvotes: 3

Views: 223

Answers (6)

xagyg
xagyg

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

PermGenError
PermGenError

Reputation: 46428

  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
    }
}

Upvotes: 6

N Olding
N Olding

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

Fyre
Fyre

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

Dino Rondelly
Dino Rondelly

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

Joe Beuckman
Joe Beuckman

Reputation: 2296

Array ints = listOfIntegers.split(' ');
print ints.inArray(integerToLookFor);

Upvotes: 0

Related Questions