-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

  • 5
    Does this answer your question? [How to extract numbers from a string and get an array of ints?](https://stackoverflow.com/questions/2367381/how-to-extract-numbers-from-a-string-and-get-an-array-of-ints) – OH GOD SPIDERS Mar 15 '21 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)); }` – Daniel Junglas Mar 15 '21 at 16:47

2 Answers2

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]
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
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.

Shaan K
  • 356
  • 1
  • 7
  • and to get an `int` of that values, use `int num1 = Integer.parseInt(val1)` –  Mar 15 '21 at 16:52