简体   繁体   中英

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 (eg "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!

  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();
//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);

}

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]);
  }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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