다음을 통해 공유


방법: 문자열 처리 메서드를 사용하여 문자열 검색(C# 프로그래밍 가이드)

System.String 클래스의 별칭인 string 형식을 사용하면 문자열의 내용을 여러 가지 방법으로 쉽게 검색할 수 있습니다.

예제

다음 예제에서는 IndexOf, LastIndexOf, StartsWithEndsWith 메서드를 사용하여 문자열을 검색합니다.

class StringSearch
{
    static void Main()
    {
        string str = "Extension methods have all the capabilities of regular static methods.";

        // Write the string and include the quotation marks.
        System.Console.WriteLine("\"{0}\"", str);

        // Simple comparisons are always case sensitive!
        bool test1 = str.StartsWith("extension");
        System.Console.WriteLine("Starts with \"extension\"? {0}", test1);

        // For user input and strings that will be displayed to the end user, 
        // use the StringComparison parameter on methods that have it to specify how to match strings.
        bool test2 = str.StartsWith("extension", System.StringComparison.CurrentCultureIgnoreCase);
        System.Console.WriteLine("Starts with \"extension\"? {0} (ignoring case)", test2);

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

        // This search returns the substring between two strings, so 
        // the first index is moved to the character just after the first string.
        int first = str.IndexOf("methods") + "methods".Length;
        int last = str.LastIndexOf("methods");
        string str2 = str.Substring(first, last - first);
        System.Console.WriteLine("Substring between \"methods\" and \"methods\": '{0}'", str2);

        // Keep the console window open in debug mode
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/*
Output:
"Extension methods have all the capabilities of regular static methods."
Starts with "extension"? False
Starts with "extension"? True (ignoring case)
Ends with '.'? True
Substring between "methods" and "methods": ' have all the capabilities of regular static '
Press any key to exit.     
*/

참고 항목

작업

방법: 정규식을 사용하여 문자열 검색(C# 프로그래밍 가이드)

개념

C# 프로그래밍 가이드

LINQ 및 문자열

기타 리소스

문자열(C# 프로그래밍 가이드)