본문 바로가기
Program Language/C#

Part1. C# 첫발 내딛기(23. 문자열 검색)

by 토담이아빠 2023. 1. 18.

문자열 검색

 

C# String 클래스에는 문자열 검색과 관련된 여러 메서드들이 있습니다. 특정 문자 및 문자열의 위치를 찾거나 문자열 안에 포함되어 있는지 여부등을 알 수 있습니다. 이번 포스팅에서는 이와 관련된 내용들을 정리하였습니다.


Contains() 메서드

 

Contains() 메서드는 문자열 내에 찾고자 하는 문자/문자열(대소문자 구분)이 포함되어 있는지 여부를 boolean 값으로 반환합니다. 포함되어 있으면 true를 리턴하고, 아니면 false를 리턴합니다.  다음은 문자열 안에서 "rabbit" 문자열이 포함되어 있는지 확인하는 예제입니다. 


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Contain_exam
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string str_src = "2023 is the year of the rabbit.";
            string str_find = "rabbit";
            bool bResult = str_src.Contains(str_find); // 문자열 포함 결과를 반환한다.

            if (bResult)
            {
                Console.WriteLine($"'{str_find}'을 찾았습니다.");
            }
            else
            {
                Console.WriteLine($"'{str_find}'을 찾지 못했습니다.");
            }
         
        }
    }
}

결과

'rabbit'를 찾았습니다.

IndexOf() 메서드

 

IndexOf() 메서드는 문자열 내에서 찾고자 하는 문자 또는 문자열의 위치, 즉 인덱스를 반환해 줍니다. 인덱스의 시작은 0부터 시작하며 찾고자 하는 문자열이 없을 때는 -1을 반환합니다. IndexOf()는 8개의 오버로드된 메서드로 구현되어 있습니다. 다음은 그중 한 가지 메서드를 이용하여 "rabbit"의 위치(index)를 반환해 주는 예제입니다.


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Contain_exam
{
    internal class Program
    {
        static void Main(string[] args)
        {

            string str_src = "2023 is the year of the rabbit.";
            string str_find = "rabbit";

            bool bResult = str_src.Contains(str_find);
            
            if (bResult)
            {
                Console.WriteLine($"'{str_find}'를 찾았습니다.");

                int nIndex = str_src.IndexOf(str_find); //문자열의 위치를 반환한다.
                Console.WriteLine($"찾은 문자(문자열)의 위치는 {nIndex}번째 입니다.");              
            }
            else
            {
                Console.WriteLine($"'{str_find}'를 찾지 못했습니다.");
            }
         
        }
    }
}

결과

'rabbit'를 찾았습니다.
찾은 문자(문자열)의 위치는 24번째 입니다.

StringComparison

 

문자열을 찾을 때 대소문자를 구분하지 않고 찾을 수 있습니다. StringComparison 열거형 안에 IgnoreCase가 들어 있는 멤버를 사용하면 대소문자를 구분하지 않습니다. IndexOf()의 오버로드 함수 중에 다음과 같이 StringComparison을 매개변수로 받는 함수가 있습니다. 


[__DynamicallyInvokable]
public int IndexOf(string value, StringComparison comparisonType)
{
    return IndexOf(value, 0, Length, comparisonType);
}

다음은 위 함수를 이용하는 예제입니다.


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Contain_exam
{
    internal class Program
    {
        static void Main(string[] args)
        {

            string str_src = "2023 is the year of the rabbit.";
            string str_find = "Rabbit";
            int nIndex = str_src.IndexOf(str_find, StringComparison.CurrentCultureIgnoreCase);     
            
            if (nIndex != -1)
            {              
                Console.WriteLine($"찾는 문자(문자열) '{str_find}' 위치는 {nIndex}번째 입니다.");              
            }
            else
            {
                Console.WriteLine($"'{str_find}'를 찾지 못했습니다.");
            }
         
        }
    }
}

결과

찾는 문자(문자열) 'Rabbit' 위치는 24번째 입니다.

참고

1. 초보자를 위한 c# 200제(2판)  / 저자 : 강병익

댓글