Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Search Strings Using String Methods (C# Programming Guide)

The string type, which is an alias for the System.String class, provides a number of useful methods for searching the contents of a string. The following example uses the IndexOf, LastIndexOf, StartsWith, and EndsWith methods.

Example

class StringSearch
{
    static void Main()
    {
        string str = "A silly sentence used for silly purposes.";
        System.Console.WriteLine("'{0}'",str);

        bool test1 = str.StartsWith("a silly");
        System.Console.WriteLine("starts with 'a silly'? {0}", test1);

        bool test2 = str.StartsWith("a silly", System.StringComparison.OrdinalIgnoreCase);
        System.Console.WriteLine("starts with 'a silly'? {0} (ignoring case)", test2);

        bool test3 = str.EndsWith(".");
        System.Console.WriteLine("ends with '.'? {0}", test3);

        int first = str.IndexOf("silly");
        int last = str.LastIndexOf("silly");
        string str2 = str.Substring(first, last - first);
        System.Console.WriteLine("between two 'silly' words: '{0}'", str2);
    }
}

Output

 
'A silly sentence used for silly purposes.'
starts with 'a silly'? False
starts with 'a silly'? True (ignore case)
ends with '.'? True
between two 'silly' words: 'silly sentence used for '

See Also

Community Additions

ADD
Show:
© 2015 Microsoft