Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 592 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fastest way to check if string contains only digits in C#

#1
I know a few ways of how to check if a string contains only digits:
RegEx, `int.parse`, `tryparse`, looping, etc.

Can anyone tell me what the *fastest* way to check is?

I need only to **CHECK** the value, no need to actually parse it.

By "digit" I mean specifically ASCII digits: `0 1 2 3 4 5 6 7 8 9`.

This is not the same question as

[To see links please register here]

, since this question is not only about how to identify, but also about what the **fastest** method for doing so is.

Reply

#2
This should work:

Regex.IsMatch("124", "^[0-9]+$", RegexOptions.Compiled)

`int.Parse` or `int.TryParse` won't always work, because the string might contain more digits that an int can hold.

If you are going to do this check more than once it is useful to use a compiled regex - it takes more time the first time, but is much faster after that.
Reply

#3
If you are concerned about performance, use neither `int.TryParse` nor `Regex` - write your own (simple) function (`DigitsOnly` or `DigitsOnly2` below, but **not** `DigitsOnly3` - LINQ seems to incur a significant overhead).

Also, be aware that `int.TryParse` will fail if the string is too long to "fit" into `int`.

This simple benchmark...

class Program {

static bool DigitsOnly(string s) {
int len = s.Length;
for (int i = 0; i < len; ++i) {
char c = s[i];
if (c < '0' || c > '9')
return false;
}
return true;
}

static bool DigitsOnly2(string s) {
foreach (char c in s) {
if (c < '0' || c > '9')
return false;
}
return true;
}

static bool DigitsOnly3(string s) {
return s.All(c => c >= '0' && c <= '9');
}

static void Main(string[] args) {

const string s1 = "916734184";
const string s2 = "916734a84";

const int iterations = 1000000;
var sw = new Stopwatch();

sw.Restart();
for (int i = 0 ; i < iterations; ++i) {
bool success = DigitsOnly(s1);
bool failure = DigitsOnly(s2);
}
sw.Stop();
Console.WriteLine(string.Format("DigitsOnly: {0}", sw.Elapsed));

sw.Restart();
for (int i = 0; i < iterations; ++i) {
bool success = DigitsOnly2(s1);
bool failure = DigitsOnly2(s2);
}
sw.Stop();
Console.WriteLine(string.Format("DigitsOnly2: {0}", sw.Elapsed));

sw.Restart();
for (int i = 0; i < iterations; ++i) {
bool success = DigitsOnly3(s1);
bool failure = DigitsOnly3(s2);
}
sw.Stop();
Console.WriteLine(string.Format("DigitsOnly3: {0}", sw.Elapsed));

sw.Restart();
for (int i = 0; i < iterations; ++i) {
int dummy;
bool success = int.TryParse(s1, out dummy);
bool failure = int.TryParse(s2, out dummy);
}
sw.Stop();
Console.WriteLine(string.Format("int.TryParse: {0}", sw.Elapsed));

sw.Restart();
var regex = new Regex("^[0-9]+$", RegexOptions.Compiled);
for (int i = 0; i < iterations; ++i) {
bool success = regex.IsMatch(s1);
bool failure = regex.IsMatch(s2);
}
sw.Stop();
Console.WriteLine(string.Format("Regex.IsMatch: {0}", sw.Elapsed));

}

}

...produces the following result...

DigitsOnly: 00:00:00.0346094
DigitsOnly2: 00:00:00.0365220
DigitsOnly3: 00:00:00.2669425
int.TryParse: 00:00:00.3405548
Regex.IsMatch: 00:00:00.7017648
Reply

#4
Here's some benchmarks based on 1000000 parses of the same string:

Updated for `release` stats:

IsDigitsOnly: 384588
TryParse: 639583
Regex: 1329571

Here's the code, looks like IsDigitsOnly is faster:

class Program
{
private static Regex regex = new Regex("^[0-9]+$", RegexOptions.Compiled);

static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
string test = int.MaxValue.ToString();
int value;

watch.Start();
for(int i=0; i< 1000000; i++)
{
int.TryParse(test, out value);
}
watch.Stop();
Console.WriteLine("TryParse: "+watch.ElapsedTicks);

watch.Reset();
watch.Start();
for (int i = 0; i < 1000000; i++)
{
IsDigitsOnly(test);
}
watch.Stop();
Console.WriteLine("IsDigitsOnly: " + watch.ElapsedTicks);

watch.Reset();
watch.Start();
for (int i = 0; i < 1000000; i++)
{
regex.IsMatch(test);
}
watch.Stop();
Console.WriteLine("Regex: " + watch.ElapsedTicks);

Console.ReadLine();
}

static bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}

return true;
}
}

Of course it's worth noting that TryParse does allow leading/trailing whitespace as well as culture specific symbols. It's also limited on length of string.
Reply

#5
You can do this in a one line LINQ statement. OK, I realise this is not necessarily the fastest, so doesn't technically answer the question, but it's probably the easiest to write:

str.All(c => c >= '0' && c <= '9')
Reply

#6
You can try using Regular Expressions by testing the input string to have only digits (0-9) by using the `.IsMatch(string input, string pattern)` method in C#.

using System;
using System.Text.RegularExpression;

public namespace MyNS
{
public class MyClass
{
public void static Main(string[] args)
{
string input = Console.ReadLine();
bool containsNumber = ContainsOnlyDigits(input);
}

private bool ContainOnlyDigits (string input)
{
bool containsNumbers = true;
if (!Regex.IsMatch(input, @"/d"))
{
containsNumbers = false;
}
return containsNumbers;
}
}
}


Regards
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through