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))));
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?
an equivalent way in C++ would be something like
std::string::const_iterator itL=find_if(spam.begin(), spam.end(),isupper);
an equivalent Python Syntax would be
next(i for i,e in enumerate(spam) if e.isupper())
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";"
the result would be: 5, 16
.
This will return expected result.
Another possibility:
string s = "0123aBc";
int rslt = -1;
var ch = s.FirstOrDefault(c => char.IsUpper(c));
if (ch != 0)
rslt = s.IndexOf(ch);
And, if you're only concerned with English:
char[] UpperCaseChars = new char[]
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z'
};
int rslt = s.IndexOfAny(UpperCaseChars);
That's probably going to execute a lot faster than any of the others, and is what I'd use if I were doing this a lot.
Another possibility is to use a regular expression:
var match = Regex.Match(s, "\p{Lu}", RegexOptions.None);
int rslt = match.Success ? match.Index : -1;
That'll match any Unicode upper case character. If you want just English, change the expression to "[A-Z]"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With