String case
In this chapter you will learn:
- How to change string case
- Compare string for different cases
- 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:
Home » C# Tutorial » String