On Thu, 07 Aug 2008 10:05:18 -0700, Ben Voigt [C++ MVP]
<rb*@nospam.nospamwrote:
>Alternatively, Andrus could use a regex of something like @"\d
+^" (Possibly $ instead of ^ - I can never remember which way round
they go.)
$ in this case, to anchor the end.
^ anchors the beginning.
LastIndexOfAny might also be a reasonable solution, though I would expect
Char.IsDigit to be faster.
Of course, if faster was the priority, calling Parse() is probably not the
preferred solution anyway. Instead, one would just scan once from the end
to find the start of the numeric string, and then go forward again,
accumulating each digit and multiplying by 10 with each new one before
adding the current digit. In other words, basically the same as what
Jon's code does, but combining the substring extraction with the parsing,
and doing it all in the same method rather than calling into the classes
(and without instantiating an intermediate string). For example:
public static int ParseNumberAtEnd(string text)
{
int i = text.Length;
int result = 0;
while (--i >= 0 && Character.IsDigit(text[i])) { }
if (i == text.Length - 1)
{
throw new ArgumentException("No digits at end");
}
while (++i < text.Length)
{
result = result * 10 + text[i] - '0';
}
return result;
}
For maintainability, I like the RegEx suggestion. It keeps all the
looping/substring mechanics hidden from view, leaving just the semantics
of "parse the number at the end of the string".
I think using LastIndexOfAny() is a reasonable alternative to RegEx, if
one finds the RegEx syntax less-than-obvious, but then you'd be stuck with
the explicit call to Substring() before Parse().
How many other ways can we skin this cat? :)
Pete