Search code examples
javastringintphrase

Java convert string to array of numbers


I would like to know is there any java function to extract all numbers from string. String examples:

"Preostalo stanje u Zicer tarifi: 248 min i 0 sec, 497 SMS, 220 MB. Tarifa vrijedi do 01.06.2015." I would like to extract 284 and 0, 497, and 220 and date.

Same function should extract other types of string like "Trenutacno imas 326 bonus MB koji ti vrijede do 02.06.2015." Where it would extract 326 and date.

String like "Imas jos 42:39 od 50 minuta razgovora. Imas jos 81 od 150 poruka. Imas jos 118,0176MB. Nemas aktiviranu opciju 1000 bonbon minuta i SMS-ova :(" ect.

I tought I can make function to walk trough string until it finds numerical char then it would phrase it, but that seems complicates.


Solution

  • Your best bet in this case would be a regular expression combined with a conversion from String to Integer. So in your case, I would do the following:

    1. Read up on regular expressions and write a regular expression that matches a number.
    2. Get all matches of that regular expression with the string that you want to extract the number from.
    3. Convert the matched substring into an integer. Luckily, there already is a method that does exactly that.