Reputation: 145
I have a string
String exp = "7 to 10";
now I am keeping a condition that
if (exp.contains("to"))
{
// here I want to fetch the integers 7 and 10
}
How to separate 7 and 10 from the string 7 to 10
(parsed as Integer
).
By using a delimiter I can obviously do it but I want to know how to do it this way?
Upvotes: 2
Views: 827
Reputation: 5868
Try following code it would work for any string.
String test="7 to 10";
String tok[]=test.split(" (\\w+) ");
for(String i:tok){
System.out.println(i);
}
Output :
7
10
Upvotes: 1
Reputation: 453
Here is the code,
import java.io.*;
public class test
{
public static void main(String[] args) {
String input="7 to 10";//pass any input here that contains delimeter "to"
String[] ans=input.split("to");
for(String result:ans) {
System.out.println(result.trim());
}
}
}
Please check and let me know if it works fine for you.
Upvotes: 1
Reputation: 10681
Using split:
if (exp.contains(" to ")) {
String[] numbers = exp.split(" to ");
// convert string to numbers
}
Using regex:
Matcher mat = Pattern.compile("(\\d+) to (\\d+)").matcher(exp);
if (mat.find()) {
String first = mat.group(1);
String second = mat.group(2);
// convert string to numbers
}
Upvotes: 8