-2

I have a String,

String a = Roll No 5 To 40;

I want to get that 5 and 40 values into Different variables, Like String b = 5 , c= 40

This values can Change to anything,like 50 TO 100 OR 10 TO 90 and so on Any Ideas How can I achieve that?

String a = Roll No 5 To 40; To get 5, I converted a into String array, Iterated on it if matches("[0-9] then append in StringBuilder Will break if T comes In case of 40, With same String "[\d]+[\d] tried matching with this pattern

Thanks in Advance Akshay

2
  • 5
    Does this answer your question? How to extract numbers from a string and get an array of ints? Commented Mar 15, 2021 at 16:39
  • One option would be to split the string on a regular expression that matches any non-empty amount of non-digits. That should leave you with precisely the items that are numbers. Those can then be converted using Integer.valueOf or similar: for (String s : text.split("\\D+")) { System.out.println(Integer.valueOf(s)); } Commented Mar 15, 2021 at 16:47

2 Answers 2

2

It is convenient to use Stream API to convert the string into int[]:

String a = "Roll No 5 To 40";


int[] ints = Arrays.stream(a.split("\\D+"))    // split the string by non-digits
                   .filter(s -> !s.isEmpty())  // ignore empty strings
                   .mapToInt(Integer::parseInt)// get int value
                   .toArray();
System.out.println(Arrays.toString(ints));

Output

[5, 40]
Sign up to request clarification or add additional context in comments.

Comments

0

If the string format is always "Roll No VAL1 To VAL2" you can do simple string manipulation:

String a = "Roll No 5 To 40";
int index_of_To = a.indexOf("To");
int index_of_No = a.indexOf("No");
String val1 = a.substring(index_of_No + 3,index_of_To).strip();
String val2 = a.substring(index_of_To + 3).strip();

Kindly note that this is a very ad hoc technique of doing this and is not very flexible.

1 Comment

and to get an int of that values, use int num1 = Integer.parseInt(val1)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.