Probably over analysing this a little bit but how would stackoverflow suggest is the best way to return an integer that is contained at the end of a string.
Thus far
Without using RegEx that can be hard to understand, or Linq and array manipulation that can be slow, a simple loop in an extension method can be used.
It can be used for long
or int
or ulong
or uint
or other while adapting the +
and -
check.
It can be adapted to parse float
and double
or decimal
too.
This method can also be written as a Parse
to have exceptions.
Implementation
static public class StringHelper
{
static public bool TryParseEndAsLong(this string str, out long result)
{
result = 0;
if ( string.IsNullOrEmpty(str) )
return false;
int index = str.Length - 1;
for ( ; index >= 0; index-- )
{
char c = str[index];
bool stop = c == '+' || c == '-';
if ( !stop && !char.IsDigit(c) )
{
index++;
break;
}
if ( stop )
break;
}
return index <= 0 ? long.TryParse(str, out result)
: long.TryParse(str.Substring(index), out result);
}
}
Test
test(null);
test("");
test("Test");
test("100");
test("-100");
test("100-200");
test("100 - 200");
test("Test 100");
test("Test100");
test("Test+100");
test("Test-100");
test("11111111111111111111");
Action test = str =>
{
if ( str.TryParseEndAsLong(out var value) )
Console.WriteLine($"\"{str}\" => {value}");
else
Console.WriteLine($"\"{str}\" has not a long at the end");
};
Output
"" has not a long at the end
"" has not a long at the end
"Test" has not a long at the end
"100" => 100
"-100" => -100
"100-200" => -200
"100 - 200" => 200
"Test 100" => 100
"Test100" => 100
"Test+100" => 100
"Test-100" => -100
"11111111111111111111" has not a long at the end