Multiple methods for determining whether a string is full of numbers and their performance comparison (C # implementation)

Source: Internet
Author: User
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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.