我不喜欢正则表达式,因为它们相对来说很慢。我们可以很容易地解决这个问题,方法是定义数字是什么,然后检查最后一个字符是否是其中之一。所以首先让我们通过指定我们认为是数字的内容来打开。
static readonly char[] numbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
现在我们需要根据最后一个字符是否是我们刚刚列出的字符之一返回两个结果之一。为此,我们使用三元语句。
var testInput = "testing5";//Testing input
var trimmedString =
numbers.Any(x => x == testInput[testInput.Length - 1]) ?//testInput.Length - 1 is going to give us the last character in the string
testInput : //It's a number so go ahead and return the full string
testInput.SubString(0, testInput.Length - 1);//It's not a number so lets return all but the last character in the string as a new string.
所以我们的最终产品看起来像这样。我将它封装到一个方法中,因为它是您代码的一个非常独立的方面(大概)。
static readonly char[] numbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public static string TrimNonNumbers(string input)
{
if (string.IsNullOrEmpty(input)) return input;//Our math will produce an index out of range exception with an empty string. So this is a safety to prevent that.
return numbers.Any(x => x == testInput[testInput.Length - 1]) ? testInput : testInput.SubString(0, testInput.Length - 1);
}