Monday, April 21, 2008

StartsWith, EndsWith

Here are a couple of useful methods that the string class provides. String.StartsWith and String.EndsWith.
List<string> names = new List<string>();
names.Add("Moeykens");
names.Add("Agee");
names.Add("Talbot");
names.Add("major");

foreach (string name in names)
{
    if (name.StartsWith("M", true, null))
        Console.WriteLine(name);
}

foreach (string name in names)
{
    if (name.EndsWith("e"))
        Console.WriteLine(name);
}
The first foreach loop will return:
Moeykens
major
The second parameter for the StartsWith method is set to "true" which tells the class to ignore case.

The second foreach will return:
Agee

More Info: MSDN: String.StartsWith
MSDN: String.EndsWith