Reputation: 21
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
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
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
Reputation: 164897
String#split()
)Stream#mapToInt()
with Integer#parseInt
and then IntStream#min()
to find the minimum valueFor example
final String s = "4 3 2 1";
final int min = Arrays.stream(s.split(" "))
.mapToInt(Integer::parseInt)
.min()
.getAsInt();
Upvotes: 2