[C# 문법] C# 문자열 내부 검색하는 방법


안녕하세요.

 

오늘은 C# 문법에서 문자열 내부를 간단하게 검색하는 방법에 대해서 알려드리려고 합니다.

 

프로젝트를 진행하시다 보면, 문자열 String 형식을 정말 많이들 사용하시고 또 내가 원하는 문자들을 찾으려는 경우가 다반사일 거라 생각합니다.


 

이때, 효율적으로 간단하게 문자열을 검색하는 방법이 있습니다. 바로 StartsWith, EndsWith, Contains 메서드를 사용하시면 됩니다. 이들 메서드 모두 반환형은 bool 형식으로써 true 또는 false를 반환합니다.

 

그럼 각각 어떻게 사용하는지 예제 코드를 통해서 알아 보도록 하겠습니다.


예제 코드


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace test12

{

    class Program

    {

        static void Main(string[] args)

        {

            //StartsWith

            Console.WriteLine("Hello. I am a 

BeomBeomJoJo.".StartsWith("Hello"));

            //EndsWith

            Console.WriteLine("Hello. I am a 

BeomBeomJoJo.".EndsWith("BeomBeomJoJo"));

            //Contains

            Console.WriteLine("Hello. I am a 

BeomBeomJoJo.".Contains("am"));

            //IndexOf

            Console.WriteLine("Hello. I am a 

BeomBeomJoJo.".IndexOf("am"));

        }

    }

}

 

Colored by Color Scripter

cs

 

실행 결과




728x90

이 글을 공유하기

댓글

Designed by JB FACTORY