Checking String for non-numbers

hi, i have a string that contains number like String="094561827"how will i check that it only has numbers from 0-9 and no non-numbers without using .contains() because it takes so long :))
[209 byte] By [Aldricha] at [2007-11-26 20:14:41]
# 1

> hi, i have a string that contains number like

> String="094561827"

>

> how will i check that it only has numbers from 0-9

> and no non-numbers without using .contains() because

> it takes so long :))

String str = "094561827";

int i=0;

boolean flag=true;

while(i < str.length())

{

if(str.charAt(i) <0 || str.charAt(i) >9 )

{

flag = false;

}

}

System.out.println("Contains only nos:"+flag);

qUesT_foR_knOwLeDgea at 2007-7-9 23:21:03 > top of Java-index,Java Essentials,Java Programming...
# 2
However i would prefer using contains( )
qUesT_foR_knOwLeDgea at 2007-7-9 23:21:03 > top of Java-index,Java Essentials,Java Programming...
# 3

I haven't tested this.

Pattern pattern=Pattern.compile("\\d{9}");

Matcher matcher=pattern.matcher("235235235");

boolean found = false;

while (matcher.find())

{

System.out.println("I found the text );

}

qUesT_foR_knOwLeDgea at 2007-7-9 23:21:03 > top of Java-index,Java Essentials,Java Programming...
# 4

Here is one easy way to do it:

try {

int val = Integer.parseInt(str);

System.out.println("value is: " + val);

} catch (NumberFormatException exc) {

System.err.println("not a number");

}

It is probably not the fastest way, though...

Geoff

glevnera at 2007-7-9 23:21:03 > top of Java-index,Java Essentials,Java Programming...
# 5
By the way, in qUesT_foR_knOwLeDge's first suggestion, I believe you want to be comparing the characters in the string to the characters '0' and '9', not the integers 0 and 9...
glevnera at 2007-7-9 23:21:04 > top of Java-index,Java Essentials,Java Programming...
# 6

Hi Aldrich!

A String is internally stored as a char[]. So you have the choice to either get each charecter with

charAt(int index)

or have everything copied to a new char array via

toCharArray()

and traverse that instead. It might turn out, that copying and traversing the array is faster than something like the following.

for (int i=0; i<test.length(); i++)

check(test.charAt(i));

(Because copying and traversing an array can be done in linear time, while the above for-loop needs n*(n+1)/2 steps for accessing all array-elements.) But haven't checked what's faster.

The check itself could look like this:

String test = "0123456789";

boolean check = true;

for (char c : test.toCharArray()) {

if (c>'9' || c<'0') {

check = false;

break;

}

}

ruehmkorfa at 2007-7-9 23:21:04 > top of Java-index,Java Essentials,Java Programming...
# 7
thank you all :)
Aldricha at 2007-7-9 23:21:04 > top of Java-index,Java Essentials,Java Programming...