Invert the case of a mixed case string (can I use regex?)


I have a string that contains a mixed bag of upper and lowercase letters.

I need to invert these (upper to lower, lower to upper) so my question is do I have to iterate through each letter and swap it or can I use a smaller, cleaner method (perhaps using a regex expression??).

Many thanks.

Who is Participating?
Put this in a method or what have you,

                string text = "SoMe CaMEL cAse TEXT.";
                char[] textarray = text.ToCharArray();
                for(int i = 0; i < textarray.Length; i++)
                    if((int)textarray[i] >= 65 && (int)textarray[i] <= 90)
                        textarray[i] = (char)((int)textarray[i] + 32);
                    else if ((int)textarray[i] >= 97 && (int)textarray[i] <= 122)
                        textarray[i] = (char)((int)textarray[i] - 32);
                string newText = new string(textarray);
i gess you will have to iterate thrtough each char, because there is no method to invert the case of the letters in string
Regular Expression is basically to model the condition or pattern and use that RegEx to check the input and decide if that satisfies the pattern or condition you want it to.

If you dont want to compare string in turn, You can Consider the use of BitMasking going to the Byte Level.
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

JAMESAuthor Commented:
OK - accepting there is no regex expression and no intrinsic method Dev's method works great - thank you!

Many thanks for your help dk but I am sure you will understand if i give the points to Dev for a such a detailed answer.

     string s="ABcdEFgh";
                  char []c=s.ToCharArray();                  
                int c1=0;
                        else if(char.IsUpper(c[c1]))
                  s=new string(c);
pradeepsudharsan & everyone,

my implementation of the method runs on average 60% faster than pradeepsudharsan version using the IsLower & IsUpper methods.

Test using 1 million iterations of a couple hundred length string.

-my version
1296 ms
1268 ms
1353 ms

avg:1305 milliseconds

-version using ToUpper & ToLower
2181 ms
2165 ms
2152 ms

avg:2166  milliseconds
Kinda suprised by the diff in speed.
JAMESAuthor Commented:
Thanks for the test results.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.