During programming, it is often necessary to determine whether all the characters in a string are numbers (0-9). This is an easy-to-implement function, but the first thing programmers will think of is, is there any ready-made function that can be used for such a simple function? VB.. NET has an IsNumeric (object). in C #, only the Char of a single character is judged. isNumber () and IsNumeric can be used to determine the double-type numeric string, but they cannot be used to exclude the plus and minus signs and decimal points. If they are used to determine whether the string is a number, however, it cannot be used to determine whether a string is composed of digits. There is no ready-made method, so I have to write the function myself:
Public static bool IsNum (String str)
{
For (int I = 0; I <str. Length; I ++)
{
If (! Char. IsNumber (str, I ))
Return false;
}
Return true;
}
Or use a regular expression: "^ d + $"
You can also use the Exception thrown by Int32.Parse () to judge:
Try
{
Int32.Parse (toBeTested );
}
Catch
{
// If an exception occurs, it is not a number.
}
Which method is the best? Each has its own advantages and disadvantages. I wrote a program to test the time required for each method. The Main () content of the test program is as follows:
Regex isNumeric = new Regex (@ "^ d + $ ");
Int times = 10000000;
Int start, end;
Int I;
String toBeTested = "6741 s ";
# Region Test user function
Start = System. Environment. TickCount;
For (I = 0; I <times; I ++)
{
TimingTest. IsNum (toBeTested );
}
End = System. Environment. TickCount;
Console. WriteLine ("User function Time:" + (end-start)/1000.0 + "Seconds ");
# Endregion
# Region Test Regular Expression
Start = System. Environment. TickCount;
For (I = 0; I <times; I ++)
{
IsNumeric. IsMatch (toBeTested );
}
End = System. Environment. TickCount;