-9

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.

musiclover
  • 1
  • 1
  • 5

4 Answers4

2

A string is immutable, so, you need to convert it to a char[].

char[] characters = text.ToCharArray();
for (int i = 0; i < characters.Length; i+=2) {
    characters[i] = char.ToUpper(characters[i]);
}
text = new string(characters);
Dennis_E
  • 8,751
  • 23
  • 29
1

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
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

Another possible solution with LINQ can be done in one line like this:

string s = "thequickbrownfoxjumpsoverthelazydog";
string result = new String(s
                            // take each character
                            .ToCharArray()
                            // convert every character at even index to upper
                            .Select ((character, index) => (index % 2) == 0 ? Char.ToUpper(character) : character)
                            // back to array in order to create a string
                            .ToArray());
Console.WriteLine(result);

The output is:

ThEqUiCkBrOwNfOxJuMpSoVeRtHeLaZyDoG

This solution uses the indexed LINQ Select clause in order to access the current index and the value that is currently projected.

keenthinker
  • 7,645
  • 2
  • 35
  • 45
0

A one liner:

new string(myString.Select((c, i) => i % 2 == 0 ? char.ToUpper(c) : c).ToArray())

An extension method:

 public static string AltCase(this string s)
 {
     return new string(s.Select((c, i) => i % 2 == 0 ? char.ToUpper(c) : c).ToArray());
 }
nullable
  • 2,513
  • 1
  • 29
  • 32