Home > front end >  C# Change indexed character of string [SOLVED]
C# Change indexed character of string [SOLVED]

Time:10-23

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);

CodePudding user response:

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 if (char.IsLower(c))
            {
                sb.Append(char.ToUpper(c));
            }
            else
            {
                sb.Append(c);
            }
        }

        Console.WriteLine(sb.ToString());

CodePudding user response:

You are not changing the input string. I would suggest you use the below code.

It will handle the cases where you have characters other than alphabets as well.

string output = new string(x.Select(c => char.IsLetter(c) ? (char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c)) : c).ToArray());
  • Related