> 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);
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 );
}
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
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;
}
}