1

I want to get the numbers of a given string and I used the code as below

String sample = "7011WD";
    String output = "";
    for (int index = 0; index < sample.length(); index++)
    {
        if (Character.isDigit(sample.charAt(index)))
        {
            char aChar = sample.charAt(index);
            output = output + aChar;
        }
    }

    System.out.println("output :" + output);

The Result is: output :7011

Is there any simple way to get the output?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
muthukumar
  • 2,233
  • 3
  • 23
  • 30

2 Answers2

6

Is there any simple way to get the output

May be you could use a regex \\D+ (D is anything which is not a digit , + means one or more occurence), and then String#replaceAll() all non-digits with empty string:

String sample = "7011WD";
String output = sample.replaceAll("\\D+","");

Though remember, using regex is not efficient at all . Also , this regex will remove the decimal points too !

You need to use Integer#parseInt(output) or Long#parseLong(output) to get the primitive int or long respectively.


You can also use Google's Guava CharMatcher. Specify the range using inRange() and return the characters from that range in sequence as a String using retainFrom().

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1

Also you can use ASCII to do this

String sample = "7011WD";
String output = "";
for (int index = 0; index < sample.length(); index++)
{

        char aChar = sample.charAt(index);
        if(int(aChar)>=48 && int(aChar)<= 57)
        output = output + aChar;
    }
}

System.out.println("output :" + output);
Shuhail Kadavath
  • 448
  • 3
  • 13
  • OP asked for a simpler way to solve this problem, I'm not sure this follows those guidelines. – Tdorno Jul 25 '13 at 05:08