Thursday, October 9, 2008

Method for comparing string

//this is a sample for Equals method
static void Main(string[] args)
{
string s1 = "foobar";
string s2 = "foobara";
if (s1.Equals(s2))//Equals method will return true or false
{
Console.WriteLine("they are the same");
}
else
{
Console.WriteLine("thet are not the same");
}
}
/////////////////////////////////////

//this is a sample for CompareTo method
static void Main(string[] args)
{
//if two strings are equal,the CompareTo method return 0.
//if the passed-in string is "below" the method string,reutrn -1.
//if the passed-in string is "above" the method-calling,return 1.
string s1 = "foobar";
string s2 = "foobar";
string s3 = "foofoo";
string s4 = "fooaar";
Console.WriteLine(s1.CompareTo(s2));
Console.WriteLine(s1.CompareTo(s3));
Console.WriteLine(s1.CompareTo(s4));
}
//this is a Compare method
static void Main(string[] args)
{
//if two strings are equal,the CompareTo method return 0.
//if the passed-in string is "below" the method string,reutrn -1.
//if the passed-in string is "above" the method-calling,return 1.
string s1 = "foobar";
string s2 = "foobar";
string s3 = "foofoo";
string s4 = "fooaar";
Console.WriteLine(String.Compare(s1,s2));
Console.WriteLine(String.Compare(s1,s3));
Console.WriteLine(String.Compare(s1,s4));
}

//this is a compare method for StartsWith and EndsWith

using System.Collections;//
namespace CompareMethodAboutString
{
class Program
{
static void Main(string[] args)
{
string[] words = new string[] { "aaa","abc","abb","baa","bca"};
ArrayList StartWithA = new ArrayList();
ArrayList EndWithA = new ArrayList();
foreach (string word in words)
{
if (word.StartsWith("a"))
{
StartWithA.Add(word);
}
if (word.EndsWith("a"))
{
EndWithA.Add(word);
}
}
foreach (string word in StartWithA)
{
Console.WriteLine(word);
}
Console.WriteLine("~~~~~~~~~~~~~~~~~~~~");
foreach (string word in EndWithA)
{
Console.WriteLine(word);
}
}
}
}

No comments: