user3853858
user3853858

Reputation: 245

How to extract integers from a complicated string?

I am having a hard time figuring with out. Say I have String like this

String s could equal

s = "{1,4,204,3}"

at another time it could equal

s = "&5,3,5,20&"

or it could equal at another time

s = "/4,2,41,23/"

Is there any way I could just extract the numbers out of this string and make a char array for example?

Upvotes: 1

Views: 98

Answers (6)

Lav
Lav

Reputation: 1896

You can use RegEx and extract all the digits from the string.

stringWithOnlyNumbers = str.replaceAll("[^\\d,]+","");

After this you can use split() using deliminator ',' to get the numbers in an array.

Upvotes: 2

gkrls
gkrls

Reputation: 2664

You can use Scanner class with , delimiter

String s = "{1,4,204,3}";

Scanner in = new Scanner(s.substring(1, s.length() - 1)); // Will scan the 1,4,204,3 part

in.useDelimiter(",");

while(in.hasNextInt()){
   int x = in.nextInt();
   System.out.print(x + " ");

   // do something with x
}

The above will print:

1 4 204 3

Upvotes: 0

user3487063
user3487063

Reputation: 3682

from your cases, if the pattern of string is same in all cases, then something like below would work, check for any exceptions, not mentioned here :

String[]  sArr= s.split(",");
sArr[0] = sArr[0].substring(1);
sArr[sArr.length()-1] =sArr[sArr.length()-1].substring(0,sArr[sArr.length()-1].length()-1);

then convert the String[] to char[] , here is an example converter method

Upvotes: 0

Jordan Bentley
Jordan Bentley

Reputation: 1309

Use regular expressions

    String a = "asdf4sdf5323ki";
    String regex = "([0-9]*)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(a);
    while (matcher.find())
    {
        String group = matcher.group(1);
        if (group.length() > 0)
        {
            System.out.println(group);
        }
    }

Upvotes: 0

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

You can use regex for this sample:

String s = "&5,3,5,20&";
System.out.println(s.replaceAll("[^0-9,]", ""));

result:

5,3,5,20

It will replace all the non word except numbers and commas. If you want to extract all the number you can just call split method -> String [] sArray = s.split(","); and iterate to all the array to extract all the number between commas.

Upvotes: 2

XsergeiX
XsergeiX

Reputation: 107

I think split() with replace() must help you with that

Upvotes: 0

Related Questions