gpt4 book ai didi

c# - 如何计算字符串末尾字母以外的所有内容

转载 作者:行者123 更新时间:2023-11-30 19:52:35 25 4
gpt4 key购买 nike

我有一个随机字符串,需要知道它末尾非字母/非数字字符数。

例如:

"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

关于c# - 如何计算字符串末尾字母以外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56393190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com