Abh*_*jit 3 c# linq string search
作为一个C#新手,目前要找出一个字符串中第一个大写字符的索引,我已经找到了一种方法
var pos = spam.IndexOf(spam.ToCharArray().First(s => String.Equals(s, char.ToUpper(s))));
Run Code Online (Sandbox Code Playgroud)
从功能上来说,代码工作正常,除了我有两次遍历字符串的不适,一次找到字符然后索引.是否有可能使用LINQ在一次传递中获取第一个UpperCase字符的索引?
C++中的等价方式就像
std::string::const_iterator itL=find_if(spam.begin(), spam.end(),isupper);
Run Code Online (Sandbox Code Playgroud)
一个等效的Python语法
next(i for i,e in enumerate(spam) if e.isupper())
Run Code Online (Sandbox Code Playgroud)
好吧,如果你只是想在做到这一点LINQ
,你可以尝试使用类似
(from ch in spam.ToArray() where Char.IsUpper(ch)
select spam.IndexOf(ch))
Run Code Online (Sandbox Code Playgroud)
如果你对字符串运行,比如说
"string spam = "abcdeFgihjklmnopQrstuv";"
Run Code Online (Sandbox Code Playgroud)
结果将是:5, 16
.
这将返回预期的结果.