Transform a string to uppercase and lowercase in C#
This article illustrates the different techniques to transform a string to uppercase and lowercase in C#.
1. Using String.ToUpper() method
A simple solution to transform a string to uppercase in C# is to invoke the String.ToUpper() instance method on your string. Since the string is immutable in C#, this method returns a copy of the string with each character converted to uppercase. The following example shows the working of the String.ToUpper() method by converting a given string to its uppercase equivalent:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = "hello"; s = s.ToUpper(); Console.WriteLine(s); // HELLO } } |
2. Using String.ToLower() method
Similarly, to get the lowercase equivalent of a string, you can use String.ToLower() method. Like String.ToUpper() method, String.ToLower() returns a new string with all characters converted to lowercase. You can use either String.ToUpper() or String.ToLower() method to transform a string for case-insensitive comparison.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = "HELLO"; s = s.ToLower(); Console.WriteLine(s); // hello } } |
3. Invert Case
If you need to invert the case of all characters in the string, you can invoke the Char.ToUpper() or Char.ToLower() method on each character of the string. This logic is demonstrated below using LINQ’s Select() method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; public class Example { public static void Main() { string s = "Hello"; var chars = s.Select(c => char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c)); var invertedCase = new string(chars.ToArray()); Console.WriteLine(invertedCase); // hELLO } } |
Note that the above solution needs the System.Linq namespace. Instead of using LINQ’s Select() method, you can also use the foreach loop to traverse the string and invert the case of each character.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { string s = "Hello"; string invertedCase = string.Empty; foreach (var c in s) { invertedCase += char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } Console.WriteLine(invertedCase); // hELLO } } |
That’s all about transforming a string to uppercase and lowercase in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)