0

I am replacing some very old c++ code that is in use at my job with a c# desktop app. In the c++ a naming convention was established that included smartcoding (yes, bad, I know but I can't change it) in some persisted object names. In the old code, if a name string begins with a number, the named object is handled with a distinct type of object (0-9 only, no other possibilities such as the Persian digits, & etc. referenced here: Is \d less efficient than [0-9]). I know there are dozens of ways to determine this and I only have to test the first character but I'm curious what's my better choice between something like this

Regex reg = new Regex("[0-9]");
bool bdistinct = reg.IsMatch(objname.Substring(0,1));

and something like this

char k0 = objname.ToCharArray(0,1)[0];
bool bdistinct = ((k0>='0')&&(k0<='9'));

or is there something else obvious and far simpler that I'm not considering?

I don't know if it makes any difference (and I guess that is an underlying question) but I don't use any RegEx references anywhere else in the replacement code (so far) which is all pretty simple stuff (very few namespaces and references in use).

Community
  • 1
  • 1

3 Answers3

3

A char comparison is going to be the fastest way to do this, note that you can access characters directly from a string for slightly cleaner code:

char k0 = objname[0];
bool bDistinct = k0 >= '0' && k0 <= '9';
  • Thanks @Bradley. I thought declaring the char variable helped phrase the question better (more analogous to the Regex solution) but you are right it was superfluous. The char comparison being faster is, I believe, the thing that is being voted up and it answers my op question completely. – Bill1260231 Jul 22 '16 at 05:49
  • Oops. I said " declaring the char variable" and left out " and assigning it explicitly" but when I noticed it was too late to fix it (5 min limit). – Bill1260231 Jul 22 '16 at 06:06
0

Try this

char k0 = objname[0];
int x = Int32.Parse(k0);
bool bDistinct = x >= 0 && x <= 9;
Barak
  • 535
  • 6
  • 18
0

The easiest way to determine if a character is a digit is to call Char.IsDigit. In your code, that would be:

bool bdistinct = Char.IsDigit(objname[0]);
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • Thanks @Jim. I had never used `IsDigit` (and forgot it existed). I'm curious now how it compares to `(k0>='0')&&(k0<='9')`. Does using `IsDigit` imply the analogous question about non-ASCII digits (referenced in my op)? (In other word, is `IsDigit` looking only at 0-9?) – Bill1260231 Jul 22 '16 at 06:01
  • [Here is the source for the `IsDigit` method](http://referencesource.microsoft.com/#mscorlib/system/char.cs,041e77a953545d16) – Bradley Moorfield Jul 22 '16 at 06:05
  • @Bill1260231: See the linked documentation for `Char.IsDigit`. – Jim Mischel Jul 22 '16 at 11:06