Search code examples
c#uppercaselowercasealternating

LowerCase and UpperCase Alternating c#


I need convert a phrase words in uppercase and lowercase continuous (alternating).

Example.

Input:
the girl is pretty.

Output:
tHe GiRl Is PrEtTy

I have tried the code below but it only convert the first letter:

char[] array = texto.ToCharArray();
if (array.Length >= 1)
{
    if (char.IsLower(array[0]))
    {
        array[0] = char.ToUpper(array[0]);
    }
}
for (int i = 1; i < array.Length; i++)
{
    if (array[i - 1] == ' ')
    {
        if (char.IsLower(array[i]))
        {
            array[i] = char.ToUpper(array[i]);
        }
    }
}
return new string(array);

Thanks


Solution

  • Fancy solution using LINQ:

    string someString = "the girl is pretty";
    string newString = string.Concat(
        someString.ToLower().AsEnumerable().Select((c, i) => i % 2 == 0 ? c : char.ToUpper(c)));
    

    This basically does the following:

    1. Convert the string to lowercase.
    2. Iterate over each character.
    3. Convert every second character to upper case.
    4. Join the characters into a single string.

    A more “classical” solution could look like this:

    string someString = "the girl is pretty";
    
    StringBuilder sb = new StringBuilder();
    bool uppercase = false;
    foreach (char c in someString)
    {
        if (uppercase)
            sb.Append(char.ToUpper(c));
        else
            sb.Append(char.ToLower(c));
    
        uppercase = !uppercase;
    }
    
    string newString = sb.ToString();