String case

In this chapter you will learn:

  1. How to change string case
  2. Compare string for different cases
  3. Change String case according to CultureInfo

Change string case

We can use ToUpper and ToLower to change the string case.

using System;/*  ja v a 2s .  co m*/

class Sample
{
    public static void Main()
    {
        string s = "java2s.com";

        Console.WriteLine(s.ToUpper());
        Console.WriteLine(s.ToLower());

    }
}

The output:

ToUpper and ToLower methods do the conversion based on user's locale.

To ignore the user's locale and do the conversion based on English locale we can use the ToUpperInvariant and ToLowerInvariant.

Compare string for different cases

using System;/*from   j  a  va 2 s  . c  o  m*/

class Main
{
  static void Main(string[] args)
  {
    char smallA = 'a';
           char largeA = 'A';

           Console.WriteLine( "a = {0} A = {1}", (int) smallA, (int) largeA );

           string str1 = "This Is A String.";
           string str2 = "This is a string.";

           Console.WriteLine( "Case sensitive comparison of str1 and str2 = {0}", String.Compare( str1, str2 ));
           Console.WriteLine( "Case insesitive comparison of str1 and str2 = {0}", String.Compare( str1, str2, true ));
  }
}

Change String case according to CultureInfo

using System;/*from  ja v  a2s  . c  om*/
using System.Globalization;


public class SamplesTextInfo  {

   public static void Main()  {
      string myString = "this Is a Test";

      TextInfo myTI = new CultureInfo("en-US",false).TextInfo;
      
      Console.WriteLine( "\"{0}\" to lowercase: {1}", myString, myTI.ToLower( myString ) );
      
      Console.WriteLine( "\"{0}\" to uppercase: {1}", myString, myTI.ToUpper( myString ) );

      Console.WriteLine( "\"{0}\" to titlecase: {1}", myString, myTI.ToTitleCase( myString ) );
   }
}

Next chapter...

What you will learn in the next chapter:

  1. How to replace substrings
  2. Replace characters
Home » C# Tutorial » String
string
String creation
Char in string
Compare strings
String equality
String concatanation
String copy
String Join
String split
String Search for Index
String contains
String start with
String insert
String case
Replacing substring
Remove from a string
Substring
Escape Characters
String verbatim
String padding
Switch on String
String trim
String intern
String normalization
Empty String