Search code examples
c#case-sensitive

How do I alternate the case in a string?


I need to alternate the case in a sentence and I don't know how to. For example:

thequickbrownfoxjumpsoverthelazydog

to

GoDyZaLeHtReVoSpMuJxOfNwOrBkCiUqEhT

this is my code so far

Console.WriteLine("Please enter a sentence:");
        string text = Console.ReadLine();
        text = text.Replace(" ", "");
        char[] reversed = text.ToCharArray();//String to char
        Array.Reverse(reversed);//Reverses char
        new string(reversed);//Char to string

        Console.WriteLine(reversed);
        Console.ReadLine();

Please note that there are no spaces for a reason as that's also part of the homework task.


Solution

  • There is no point to reverse your string. Just upper case your even number indexed characters in your string.

    Remember, my culture is tr-TR and this String.ToUpper method works depends on your current thread culture. In this example, your output can be different than mine.

    Here an example in LINQPad;

    string s = "thequickbrownfoxjumpsoverthelazydog";
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.Length; i++)
    {
        if (i % 2 == 0)
        {
            sb.Append(s[i].ToString().ToUpper());
        }
        else
        {
            sb.Append(s[i].ToString());
        }
    }
    sb.ToString().Dump();
    

    Output will be;

    ThEqUiCkBrOwNfOxJuMpSoVeRtHeLaZyDoG