John Smith
John Smith

Reputation: 21

Find minimum number of a sequence of numbers in a string

I am confused as how to separate a sequence of numbers in a string, which are separated by spaces and finding the minimum among them (e.g. "4 3 2 1".)I have an idea of separating the values using a scanner and parsing them, but I don't know how to use them when it's a string. Please help! Thanks!

Upvotes: 1

Views: 1893

Answers (4)

Ghostranger
Ghostranger

Reputation: 85

For Splitting the String you can use (For Example):

String str = "4 3 2 1";
String[] splited = str.split("\\s+");

as for the individual number in the array "splited" you can use

int Num = Integer.parseInt(splited[INDEX]);

or you can directly use the Integer.parseInt(Splited[INDEX]) in the condition of IF loop.

int min=Integer.parseInt(splited[0]);
for(int i=1;i<splited.length;i++){
  if(min > Integer.parseInt(splited[i])){
     min = Integer.parseInt(splited[i]);
  }
}

Upvotes: 0

DhaRmvEEr siNgh
DhaRmvEEr siNgh

Reputation: 2098

//hope this helps

public static void main(String[] args){
    String s = "9 3 4 5 7 3 8 9 3 1";
   //split on space
    String[] arr = s.split(" ");

    int result = Integer.parseInt(arr[0]), temp;
    for(int i = 1; i<arr.length; i++) {
                temp = Integer.parseInt(arr[i]);
    //store lowest in result
        if(result>temp)
            if(temp<result) {
                result = temp;
            }
    }

//print result
System.out.println(result);

}

Upvotes: 1

Phil
Phil

Reputation: 164897

  1. Split the string on space (ie String#split())
  2. Pass the array to a stream
  3. Use Stream#mapToInt() with Integer#parseInt and then IntStream#min() to find the minimum value

For example

final String s = "4 3 2 1";
final int min = Arrays.stream(s.split(" "))
    .mapToInt(Integer::parseInt)
    .min()
    .getAsInt();

Upvotes: 2

Vj-
Vj-

Reputation: 722

There are parsers for each datatype. In your case you need to parse a string into an int, so do

Integer.parseInt(str);

Here is the javadoc.

Upvotes: -1

Related Questions