Search code examples
c#char

Change indexed character of string


Im working on a program that changes a specified character, if its uppercase, it will change it to lowercase and vice versa.

I have written a piece of code that in theory should work. I have also written it with a foreach(char c in x) method but that wont work wither. Any tips?

Expected output teSTSTring Given output TEststRING

            string x = "TEststRING";

            for (int i = 0; i < x.Length; i++)
            {
                if (char.IsUpper(x[i]))
                {
                    char.ToLower(x[i]);
                }
                if (char.IsLower(x[i]))
                {
                    char.ToUpper(x[i]);
                }
            }

            Console.WriteLine(x);

Solution

  • Here is a solution with StringBuilder

    string x = "TEststRING";
    car sb = new StringBuilder();
    
    foreach (car c in x)
    {
        if (char.IsUpper(c))
        {
            sb.Append(char.ToLower(c));
        }
        else
        {
            sb.Append(char.ToUpper(c));
        }    
    }
    
    Console.WriteLine(sb.ToString());