[英]How to count everything but letters at end of a string
我有一个随机字符串,需要知道它末尾的非字母/非数字字符的数量 。
例如:
"Some text."
应该导致1
"More text 123 !.?"
应该导致4 (包括空格)
"Even more text 123"
应该导致0
我怎样才能做到这一点?
您可以尝试Linq :
string source = "More text 123 !.?";
int result = source
.Reverse()
.TakeWhile(c => !char.IsLetterOrDigit(c))
.Count();
演示:
string[] tests = new string[] {
"Some text.",
"More text 123 !.?",
"Even more text 123"
};
string demo = string.Join(Environment.NewLine, tests
.Select(s => $"{s,-30} : {s.Reverse().TakeWhile(c => !char.IsLetterOrDigit(c)).Count()}"));
Console.Write(demo);
结果:
Some text. : 1
More text 123 !.? : 4
Even more text 123 : 0
使用Linq的问题是Enumerable.Reverse()
将字符串的副本作为char数组并向后迭代它,这是无效的。 这对你来说可能并不重要,但更有效的方法是在字符串的字符上向后循环,如下所示:
string test = "the string to test !*&*& ";
int i;
for (i = test.Length - 1; i >= 0 && !char.IsLetterOrDigit(test[i]); --i)
;
int n = test.Length - i - 1; // n is the count of non-letter/non-digit chars
如果你想要它作为一种方法来调用:
public static int CountNonLetterDigitCharsAtEnd(string input)
{
int i;
for (i = input.Length - 1; i >= 0 && !char.IsLetterOrDigit(input[i]); --i)
;
return input.Length - i - 1;
}
您可以向后遍历字符串并使用Char.IsLetterOrDigit来确定它是否是非字母数字。 当您找到一个字母或数字时,然后停止并返回计数。
LINQ很容易:
using System.Linq;
此函数还处理空字符串并为它们返回-1。
public static int CountNonLettersAtEnd(string input)
=> input?.Reverse().TakeWhile(c => !char.IsLetterOrDigit(c)).Count() ?? -1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.