본문 바로가기
.NET

C# split 사용 방법

by leo21c 2023. 1. 19.
SMALL

https://learn.microsoft.com/ko-kr/dotnet/csharp/how-to/parse-strings-using-split

 

String.Split을 사용하여 문자열 나누기(C# 가이드)

Split 메서드는 구분 기호 세트에서 분리된 문자열 배열을 반환합니다. 문자열에서 부분 문자열을 추출하는 간편한 방법입니다.

learn.microsoft.com


char[] delimiterChars = { ' ', ',', '.', ':', '\t' };

string text = "one\ttwo three:four,five six seven";
System.Console.WriteLine($"Original text: '{text}'");

string[] words = text.Split(delimiterChars);
System.Console.WriteLine($"{words.Length} words in text:");

foreach (var word in words)
{
    System.Console.WriteLine($"<{word}>");
}

샘플 코드는 위와 같이 char array를 넣어서 사용을 한다.

하나의 구분자를 가지고 나눌 경우에는 아래와 같이 하면 편하게 이용할 수 있다.


string text = "one\ttwo three:four,five six seven";
System.Console.WriteLine($"Original text: '{text}'");

string[] words = text.Split(new char[] { '.' });
System.Console.WriteLine($"{words.Length} words in text:");

foreach (var word in words)
{
    System.Console.WriteLine($"<{word}>");
}

string[] words = text.Split(new char[] { '.' });

위와 같이 new로 생성을 해서 하나의 구분자를 이용하는 것이다.

 

LIST