C#에서 문자열에 공백이 포함되어 있을 때는 Split() 메서드를 사용하면 공백을 기준으로 문자열을 손쉽게 나눌 수 있습니다. 이 글에서는 기본적인 사용법부터 전체 예제 코드와 실행 결과까지 단계별로 살펴보겠습니다.
1. 분할할 문자열 준비하기
먼저 공백을 포함한 문자열을 하나 선언합니다.
string str = "Science and Mathematics";
2. Split() 메서드로 공백 기준 분할하기
Split() 메서드에 구분자로 공백 문자(' ')를 전달하면, 공백이 나타나는 위치마다 문자열이 잘려서 string[] 배열 형태로 반환됩니다.
str.Split(' ')3. 전체 예제 코드
다음은 위 내용을 모두 합친 완성된 코드입니다.
using System;
using System.Linq;
using System.IO;
class Program {
static void Main() {
string str = "Science and Mathematics";
Console.WriteLine("String...\n" + str);
string[] myStr = str.Split(' ');
Console.WriteLine("\nSplitted String...");
foreach (string ch in myStr) {
Console.WriteLine(ch);
}
}
}
실행 결과
String...
Science and Mathematics
Splitted String...
Science
and
Mathematics
참고: 연속된 공백 처리하기
문자열에 공백이 여러 개 연속으로 포함되어 있으면, 기본 Split() 호출 시 빈 문자열이 배열에 함께 들어갈 수 있습니다. 이런 경우 StringSplitOptions.RemoveEmptyEntries 옵션을 추가하면 빈 항목을 자동으로 제거하여 더 깔끔한 결과를 얻을 수 있습니다.
string[] result = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);Split() 메서드는 콤마, 탭 등 다른 구분자에도 동일하게 적용할 수 있으므로, 텍스트 파싱 작업에서 매우 유용하게 활용됩니다.