String equality
In this chapter you will learn:
String comparison for equality
We can use == to check the equality between two string values
using System;/*from ja va2s . c o m*/
class Sample
{
public static void Main()
{
string s1 = "java2s.com";
string s2 = "java2s.coM";
if (s1.ToUpper() == s2.ToUpper())
{
Console.WriteLine("equal");
}
}
}
The output:
Equals method
Equals
method from string type
provides the same functionality and adds more features.
using System;// j a va2 s. co m
class Sample
{
public static void Main()
{
string s1 = "java2s.com";
string s2 = "java2s.coM";
if (s1.ToUpper().Equals(s2.ToUpper()))
{
Console.WriteLine("equal");
}
}
}
The output:
Compare and ignore case
Further more we can compare two string ignoring the case by specifying case-insensitive option.
using System;//from j a v a 2s . co m
class Sample
{
public static void Main()
{
string s1 = "java2s.com";
string s2 = "java2s.coM";
if (s1.Equals(s2, StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("equal");
}
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- Use the Concat() method to concatenate strings
- Use the addition operator (+) to concatenate strings
- Concat method with a String array
- Mix string and integer in string cancatenation
Home » C# Tutorial » String