查找第一个大写字符的索引 [英] Find Index of the First Uppercase character

查看:69
本文介绍了查找第一个大写字符的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为C#新手,目前正在寻找一种方法找出字符串中第一个大写字符的索引

As a C# Novice, currently to find out the index of the first uppercase character in a string I have figured out a way

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

在功能上,代码工作正常,除了我不舒服地遍历字符串两次,一次是找到字符,然后是索引.是否有可能使用LINQ一次性获得第一个UpperCase字符的索引?

Functionally the code works fine except that I was having the discomfort of traversing the string twice, once to find the Character and then the Index. Is there any possibility to get the index of the first UpperCase character in one pass using LINQ?

C ++中的一种等效方法将是

an equivalent way in C++ would be something like

std::string::const_iterator itL=find_if(spam.begin(), spam.end(),isupper);

等效的Python语法为

an equivalent Python Syntax would be

next(i for i,e in enumerate(spam) if e.isupper())

推荐答案

好吧,如果您只是想想要LINQ中进行操作,则可以尝试使用

Well, if you just want to do it in LINQ, you can try to use something like

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

如果针对字符串运行此命令,请说

If you run this against string, say

"string spam = "abcdeFgihjklmnopQrstuv";"

结果将是:5, 16.

这将返回预期结果.

这篇关于查找第一个大写字符的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆