Compare strings
In this chapter you will learn:
- What are the methods we can use to compare strings
- Compare string case sensitively
- Compare string with start index and end index
- Compare strings using StringComparison enumeration: InvariantCulture
Methods used to compare strings
The compare methods from string has the following syntax:
public static int Compare (string strA, string strB, StringComparison comparisonType);
public static int Compare (string strA, string strB, bool ignoreCase, CultureInfo culture);
public static int Compare (string strA, string strB, bool ignoreCase);
public static int CompareOrdinal (string strA, string strB);
The return value:
Return Value | Condition |
---|---|
< 0 | This instance precedes strB. |
0 | This instance has the same position in the sort order as strB. |
>0 | This instance follows strB. -or- strB is null. |
using System;/*j a v a2 s . c o m*/
class Program
{
static void Main(string[] args)
{
string s1 = "abc";
string s2 = "def";
int result = s1.CompareTo(s2);
Console.WriteLine(result);
}
}
The output:
Compare string case sensitively
using System; // j a va 2s . c o m
class MainClass {
public static void Main() {
string str1 = "one";
string str2 = "ONE";
if(String.Compare(str1, str2, true) == 0)
Console.WriteLine(str1 + " and " + str2 +
" are equal ignoring case.");
else
Console.WriteLine(str1 + " and " + str2 +
" are not equal ignoring case.");
}
}
The code above generates the following result.
Compare string with start index and end index
using System; /* j a v a 2 s. c o m*/
class MainClass {
public static void Main() {
string str1 = "one";
string str2 = "one, too";
if(String.Compare(str1, 0, str2, 0, 3) == 0)
Console.WriteLine("First part of " + str1 + " and " +
str2 + " are equal.");
else
Console.WriteLine("First part of " + str2 + " and " +
str2 + " are not equal.");
}
}
The code above generates the following result.
Compare strings using StringComparison enumeration: InvariantCulture
using System; /*from jav a2 s. c om*/
class MainClass {
public static void Main() {
string pswd = "asdf";
string str = "fda";
// Compare using invariant culture.
if(String.Compare(pswd, str,
StringComparison.InvariantCulture) == 0)
Console.WriteLine("Password accepted.");
else
Console.WriteLine("Password invalid.");
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » String