string s = "This is an ExAmPlE of sTrInG";
Such words in this string: 2.
I understand how to convert a phrase to uppercase and lowercase words but i dont know how to find such words in string and count it
string s = "This is an ExAmPlE of sTrInG";
Such words in this string: 2.
I understand how to convert a phrase to uppercase and lowercase words but i dont know how to find such words in string and count it
This should do the trick:
First you need to split the string in words and than you can check each word if is alternating
public void Counter(string phrase)
{
var qty = 0;
var words = phrase.Split(' ');
for (var i = 0; i < words.Length; ++i)
{
if (IsUpperLowerAltenated(words[i].Trim()))
++qty;
}
}
public bool IsUpperLowerAltenated(string word)
{
for (var i = 1; i < word.Length; ++i)
{
if(char.IsLower(word[i-1]) == char.IsLower(word[i]))
return false;
}
return true;
}
String is mixed case if it's not either lower or upper
bool IsUpper(string str) => str.Upper() == str;
bool IsLower(string str) => str.Lower() == str;
bool IsMixedCase(string str) => !IsUpper(str) && !IsLower(str);
string s = "This is an ExAmPlE of sTrInG";
foreach (var str in s.Split().Where(IsMixedCase))
{
Console.WriteLine(str);
}
Solution without explicit loop. String is alternating if each pair of characters in different cases
public static IEnumerable<(T, T)> Pairwise<T>(this IEnumerable<T> input)
=> input.Zip(input.Skip(1), (a, b) => (a, b));
public static bool OfDifferentCase(char c1, char c2)
=> char.IsUpper(c1) && char.IsLower(c2) || char.IsLower(c1) && char.IsUpper(c2);
public static bool IsAlternating(string str)
=> str.Pairwise().All(p => OfDifferentCase(p.Item1, p.Item2));
string s = "This is an ExAmPlE of sTrInG";
foreach (var str in s.Split().Where(IsAlternating))
{
Console.WriteLine(str);
}
You can find count of upper and lower chars like this.
public int IsUpperCount(string myString)
{ int upperC=0;
var charArray = myString.ToCharArray();
foreach (var item in charArray)
{
if(item.toString()==item.toString().ToUpper())
{ upperC++;}
return upperC;
}
public int IsLowerCount(string myString)
{ int lowerC=0;
var charArray = myString.ToCharArray();
foreach (var item in charArray)
{
if(item.toString()==item.toString().ToUpper())
{ lowerC++;}
return lowerC;
}
string s = "This is an ExAmPlE of sTrInG";
var words = Regex.Matches(s, @"\b((\p{Ll}\p{Lu})+\p{Ll}?|(\p{Lu}\p{Ll})+\p{Lu}?)\b");
foreach (var w in words)
{
Console.WriteLine(w);
}
Reference:
Regex pattern search for alternating character case
RegEx for matching alternating case letters
Make regular expression not match empty string?
regex - match pattern of alternating characters
Supported Unicode general categories