作为 C# 新手,目前为了找出字符串中第一个大写字符的索引,我想出了一个方法

var pos = spam.IndexOf(spam.ToCharArray().First(s => String.Equals(s, char.ToUpper(s))));

从功能上讲,代码工作正常,除了我对遍历字符串两次感到不适,一次是为了找到字符,然后是索引。是否有可能使用 LINQ 一次性获得第一个大写字符的索引?

C++ 中的等效方法类似于
std::string::const_iterator itL=find_if(spam.begin(), spam.end(),isupper);

等效的 Python 语法是
next(i for i,e in enumerate(spam) if e.isupper())

最佳答案

好吧,如果你只是想在 LINQ 中做到这一点,你可以尝试使用类似的东西

(from ch in spam.ToArray() where Char.IsUpper(ch)
         select spam.IndexOf(ch))

如果你对字符串运行这个,说
"string spam = "abcdeFgihjklmnopQrstuv";"

结果将是: 5, 16

这将返回预期的结果。

关于c# - 查找第一个大写字符的索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10257711/

10-13 00:08