Showing posts with label String Methods. Show all posts
Showing posts with label String Methods. Show all posts

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

Tuesday, April 1, 2008

String.IsNullOrEmpty method

Returns true if the string passed in is null or empty. Otherwise returns false.
Before:
if (name == null || name == string.Empty)) 
{
     return "Please enter a name."; 
}
After:
if (string.IsNullOrEmpty(name)) 
{     
    return "Please enter a name."; 
}
More Info: MSDN: String.IsNullOrEmpty