푸터 콘텐츠로 바로가기
.NET 도움말

C# 문자열 분할 (개발자를 위한 작동 방식)

프로그래밍을 처음 접하는 사람이나 성장하는 C# 개발자 모두에게 문자열을 분할하는 방법을 이해하는 것은 코딩 능력을 크게 향상시킬 수 있는 기본 기술입니다. 이번 튜토리얼에서는 C#에서의 분할 조작을 깊이 탐구할 것입니다.

문자열 분할 도입

프로그래밍에서 문자열은 문자들의 시퀀스이며, 특정 구분자 또는 델리미터를 기준으로 이를 더 작은 부분으로 나누어야 할 시나리오가 있습니다. 이 과정은 문자열 분할이라고 불리며, 텍스트 데이터를 처리할 때 필수적인 기술입니다. 문장이 있고, 이를 개별 단어로 나누고자 한다고 상상해보세요 – 이것이 문자열 분할의 고전적인 예입니다.

C#에서, String.Split() 는 이 작업에 대한 보편적인 도구입니다. 분할 메서드는 주어진 구분자를 기준으로 문자열을 여러 부분으로 나누어 배열로 변환할 수 있게 해 줍니다. 이 메서드를 효과적으로 사용하는 다양한 측면을 탐구해 봅시다.

String.Split() 사용하기

기본 문자열 분할

String.Split() 메서드의 가장 간단한 사용법은 단일 문자 구분 기호를 제공하는 것입니다. 문장을 단어로 분할하는 방법은 다음과 같습니다:

// Define a sentence to split
string sentence = "Hello, world! Welcome to C# programming.";
// Define the character separator
char separator = ' '; // Space character
// Split the sentence into words
string[] words = sentence.Split(separator);
// Define a sentence to split
string sentence = "Hello, world! Welcome to C# programming.";
// Define the character separator
char separator = ' '; // Space character
// Split the sentence into words
string[] words = sentence.Split(separator);
' Define a sentence to split
Dim sentence As String = "Hello, world! Welcome to C# programming."
' Define the character separator
Dim separator As Char = " "c ' Space character
' Split the sentence into words
Dim words() As String = sentence.Split(separator)
$vbLabelText   $csharpLabel

이 예제에서는 문장이 문자열 배열로 나뉘어 있으며, 각 요소는 단어를 나타냅니다. 여기서 구분자는 공백 문자입니다. 문자열을 구분하는 기준을 변경하여 쉼표, 세미콜론 또는 원하는 다른 문자를 기준으로 문자열을 분할할 수 있습니다.

빈 배열 요소 처리

때때로 문자열을 분할할 때 연속적인 구분자가 빈 배열 요소를 초래하는 상황에 직면할 수 있습니다. 예를 들어, 문자열 apple,,banana,orange 를 고려해보세요. 이 문자열을 쉼표를 구분자로 사용하여 분할하면 연속된 쉼표 사이에 빈 요소를 포함하는 배열이 생깁니다.

이를 처리하기 위해, StringSplitOptions.RemoveEmptyEntries 옵션을 사용할 수 있습니다:

// Define a string with consecutive separators
string fruits = "apple,,banana,orange";
char separator = ','; // Separator character

// Split and remove empty entries
string[] fruitArray = fruits.Split(new char[] { separator }, StringSplitOptions.RemoveEmptyEntries);
// Define a string with consecutive separators
string fruits = "apple,,banana,orange";
char separator = ','; // Separator character

// Split and remove empty entries
string[] fruitArray = fruits.Split(new char[] { separator }, StringSplitOptions.RemoveEmptyEntries);
' Define a string with consecutive separators
Dim fruits As String = "apple,,banana,orange"
Dim separator As Char = ","c ' Separator character

' Split and remove empty entries
Dim fruitArray() As String = fruits.Split(New Char() { separator }, StringSplitOptions.RemoveEmptyEntries)
$vbLabelText   $csharpLabel

이 옵션을 사용하면 연속 구분자로 인해 발생한 빈 배열 요소가 자동으로 결과 배열에서 제거됩니다.

다중 구분자로 분할하기

더 복잡한 시나리오에서는 여러 문자를 구분자로 사용하여 문자열을 분할해야 할 수 있습니다. 예를 들어, 문자열 apple;banana orange 를 가지고 세미콜론과 공백을 구분 기호로 사용하여 그것을 분할하려고 한다고 상상해보세요.

이를 위해서는 string.Split() 메서드를 params char 매개변수와 함께 사용할 수 있습니다:

// Define a string with multiple delimiters
string fruits = "apple;banana orange";
char[] separators = { ';', ' ' }; // Multiple separators

// Split the string using multiple delimiters
string[] fruitArray = fruits.Split(separators);
// Define a string with multiple delimiters
string fruits = "apple;banana orange";
char[] separators = { ';', ' ' }; // Multiple separators

// Split the string using multiple delimiters
string[] fruitArray = fruits.Split(separators);
' Define a string with multiple delimiters
Dim fruits As String = "apple;banana orange"
Dim separators() As Char = { ";"c, " "c } ' Multiple separators

' Split the string using multiple delimiters
Dim fruitArray() As String = fruits.Split(separators)
$vbLabelText   $csharpLabel

그러면 세 개의 요소를 가진 배열을 얻을 수 있습니다: apple, banana, 그리고 orange.

부분 문자열 개수 제한

일부 경우 문자열을 제한된 부분 문자열 개수로 분할하고 싶을 수 있습니다. 이는 긴 문자열을 처리하거나 특정 개수의 세그먼트에만 관심이 있을 때 유용할 수 있습니다. String.Split() 메서드는 생성할 최대 하위 문자열 수를 지정할 수 있게 해줍니다:

// Define a long string to split
string longString = "one,two,three,four,five";
char separator = ','; // Separator character
int maxSubstrings = 3; // Limit to the first three substrings

// Split the string with a limit on the number of substrings
string[] firstThreeItems = longString.Split(separator, maxSubstrings);
// Define a long string to split
string longString = "one,two,three,four,five";
char separator = ','; // Separator character
int maxSubstrings = 3; // Limit to the first three substrings

// Split the string with a limit on the number of substrings
string[] firstThreeItems = longString.Split(separator, maxSubstrings);
' Define a long string to split
Dim longString As String = "one,two,three,four,five"
Dim separator As Char = ","c ' Separator character
Dim maxSubstrings As Integer = 3 ' Limit to the first three substrings

' Split the string with a limit on the number of substrings
Dim firstThreeItems() As String = longString.Split(separator, maxSubstrings)
$vbLabelText   $csharpLabel

maxSubstrings 매개변수를 3 로 설정하면, 결과 배열은 one, two, 그리고 three 를 포함하게 됩니다. 문자열의 나머지 부분 (four,five) 은 손대지 않은 채로 남아 있습니다.

자신만의 문자열 분할 확장 만들기

내장된 String.Split() 메서드는 대부분의 문자열 분할 요구를 충족하지만, 기능을 요구에 맞게 조정하기 위해 자체 확장 메서드를 만들 수도 있습니다. 예를 들어, 단일 문자가 아닌 특정 부분 문자열을 기준으로 문자열을 분할하고자 한다고 가정해봅시다. 방법은 다음과 같습니다.

using System;

namespace StringSplitExtension
{
    // Define a static class to hold the extension method
    public static class StringExtensions
    {
        // Extension method for splitting a string by a substring
        public static string[] SplitBySubstring(this string input, string s)
        {
            return input.Split(new string[] { s }, StringSplitOptions.None);
        }
    }

    // Test the extension method
    class Program
    {
        static void Main(string[] args)
        {
            string text = "apple+banana+orange";
            string separator = "+"; // Substring separator

            // Use the custom extension method to split the string
            string[] result = text.SplitBySubstring(separator);
            foreach (string item in result)
            {
                Console.WriteLine(item);
            }
        }
    }
}
using System;

namespace StringSplitExtension
{
    // Define a static class to hold the extension method
    public static class StringExtensions
    {
        // Extension method for splitting a string by a substring
        public static string[] SplitBySubstring(this string input, string s)
        {
            return input.Split(new string[] { s }, StringSplitOptions.None);
        }
    }

    // Test the extension method
    class Program
    {
        static void Main(string[] args)
        {
            string text = "apple+banana+orange";
            string separator = "+"; // Substring separator

            // Use the custom extension method to split the string
            string[] result = text.SplitBySubstring(separator);
            foreach (string item in result)
            {
                Console.WriteLine(item);
            }
        }
    }
}
Imports System

Namespace StringSplitExtension
	' Define a static class to hold the extension method
	Public Module StringExtensions
		' Extension method for splitting a string by a substring
		<System.Runtime.CompilerServices.Extension> _
		Public Function SplitBySubstring(ByVal input As String, ByVal s As String) As String()
			Return input.Split(New String() { s }, StringSplitOptions.None)
		End Function
	End Module

	' Test the extension method
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			Dim text As String = "apple+banana+orange"
			Dim separator As String = "+" ' Substring separator

			' Use the custom extension method to split the string
			Dim result() As String = text.SplitBySubstring(separator)
			For Each item As String In result
				Console.WriteLine(item)
			Next item
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

이 예에서는 하위 문자열 구분 기호를 입력으로 받고 주어진 구분 기호와 함께 내장된 String.Split() 메서드를 사용하는 SplitBySubstring 이라는 확장을 정의합니다. 이 접근 방식은 C#의 string 클래스의 기능을 확장하면서 코드의 구성을 유지하고 재사용 가능하게 만듭니다.

Iron Suite: C#을 위한 강력한 라이브러리 컬렉션

Iron Suite는 C# 개발자를 위한 강력한 도구 세트로 다양한 도메인에서 고급 기능을 제공합니다. 문서 조작부터 광학 문자 인식 (OCR)에 이르는 이러한 라이브러리는 현대 개발 도구 세트의 필수 부분입니다. 흥미롭게도, 이것들은 C#의 근본적인 문자열 조작 함수인 String.Split() 메서드와 관련이 있을 수 있습니다.

IronPDF: HTML을 PDF로 변환

IronPDF는 개발자가 .NET 애플리케이션 내에서 HTML을 직접 PDF로 렌더링할 수 있게 해줍니다. 이 강력한 라이브러리는 PDF 콘텐츠 생성, 편집, 추출까지 지원합니다. 직관적인 API를 제공하여 문자열 조작처럼 간단하게 PDF 조작이 가능합니다. IronPDF 사용에 대한 추가 정보, 튜토리얼 및 안내는 IronPDF의 웹사이트HTML to PDF 튜토리얼을 방문하세요.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

IronXL: 엑셀 작업의 탁월함

C# 애플리케이션 내에서 Excel 파일을 다루는 경우 IronXL은 필수적인 라이브러리입니다. IronXL은 개발자가 C#을 통해 문자열 조작을 처리하는 것처럼 Excel 파일을 쉽게 읽고, 쓰고, 조작할 수 있게 합니다.

IronOCR: 광학 문자 인식

IronOCR는 OCR 기능을 애플리케이션에 통합하는 개발자에게 필수적인 라이브러리입니다. IronOCR를 활용하면 이미지와 스캔된 문서에서 텍스트를 읽어 C# Split String을 사용하여 조작할 수 있는 관리 가능한 문자열로 변환할 수 있습니다. IronOCR 웹사이트를 방문하여 IronOCR에 대한 자세한 내용과 프로젝트에 통합하는 방법을 알아보세요.

IronBarcode: 바코드 스캔 및 생성

마지막으로, Iron Suite는 IronBarcode를 포함하여 C# 애플리케이션 내에서 바코드를 읽고 생성하는 포괄적인 솔루션을 제공합니다. 이 라이브러리는 바코드 작업의 복잡성을 문자열 조작처럼 간단한 수준으로 낮춥니다.

결론

Iron Suite는 IronPDF, IronXL, IronOCR, IronBarcode의 다양한 구성요소로 구성되어 있으며, PDF, Excel 파일, OCR 및 바코드 작업을 하는 개발자를 위한 간단한 솔루션을 제공합니다. C# Split String 메소드가 문자열 조작을 간단하게 하듯이, 이러한 라이브러리는 복잡한 작업을 단순화하여 현대 개발자에게 훌륭한 도구들입니다.

이 놀라운 제품 각각은 모든 기능을 탐색하고 실험해볼 수 있도록 무료 체험판을 제공합니다. 각 제품의 라이센싱은 liteLicense 에서 시작되어 고급 기능으로의 경제적인 진입점을 제공합니다.

Iron Suite 전체 패키지는 개별 제품 두 개만큼의 가격으로 구매할 수 있습니다. 이 번들 제공은 개발 도구 키트의 기능을 확장시켜줄 뿐만 아니라 훌륭한 가치를 제공합니다.

자주 묻는 질문

String.Split() 메서드가 C#에서 어떻게 작동하나요?

C#의 String.Split() 메서드는 지정된 구분 문자에 따라 문자열을 하위 문자열의 배열로 나눕니다. 이는 문자열 데이터를 효율적으로 구문 분석하고 관리하는 데 유용합니다.

C#에서 문자열을 나누는 몇 가지 고급 방법은 무엇인가요?

C#의 고급 문자열 분할방법에는 여러 구분자 사용, StringSplitOptions.RemoveEmptyEntries를 통한 빈 항목 제거, 그리고 Split 메서드의 추가 매개변수를 사용해 하위 문자열 수를 제한하는 방법 등이 포함됩니다.

C#에서 문자열을 나누기 위한 사용자 정의 메서드를 만들 수 있나요?

네, 확장 메서드를 정의하여 사용자 정의 문자열 분할 기능을 만들 수 있습니다. 예를 들어, SplitBySubstring 확장을 사용하여 단일 문자가 아닌 특정 하위 문자열에 따라 문자열을 분할할 수 있습니다.

C# 개발자를 위한 Iron Suite는 무엇인가요?

Iron Suite는 C# 개발을 향상시키기 위해 설계된 강력한 라이브러리 모음입니다. PDF 조작을 위한 IronPDF, Excel 작업을 위한 IronXL, 광학 문자 인식을 위한 IronOCR, 바코드 생성을 위한 IronBarcode 등이 포함됩니다.

C# 응용 프로그램에서 HTML을 PDF로 변환하는 방법은 무엇인가요?

IronPDF의 RenderHtmlAsPdf 메서드를 사용하여 HTML 문자열을 PDF로 변환할 수 있습니다. 또한 RenderHtmlFileAsPdf 메서드를 사용하여 HTML 파일을 PDF로 변환할 수도 있습니다.

C# 응용 프로그램을 위한 IronOCR의 기능은 무엇인가요?

IronOCR은 C# 응용 프로그램에 광학 문자 인식을 통합하여 이미지 및 스캔된 문서의 텍스트를 읽고 편집 가능한 문자열로 변환할 수 있도록 지원합니다.

Iron Suite의 라이센싱 옵션은 무엇인가요?

Iron Suite는 각 제품의 무료 체험판을 제공하며, 라이센싱은 'liteLicense'부터 시작합니다. 전체 Suite 패키지는 개별 제품 두 개의 가격으로 제공되어 개발자들에게 훌륭한 가치를 제공합니다.

IronPDF는 .NET에서 PDF 조작을 어떻게 단순화하나요?

IronPDF는 .NET 응용 프로그램에서 PDF 내의 콘텐츠 생성, 편집, 추출을 위한 직관적인 API를 제공하여 개발자가 PDF 조작을 간단하고 효율적으로 할 수 있도록 합니다.

제이콥 멜러, 팀 아이언 최고기술책임자
최고기술책임자

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.

제이콥은 맨체스터 대학교에서 토목공학 학사 학위(BEng)를 최우등으로 취득했습니다(1998~2001). 1999년 런던에서 첫 소프트웨어 회사를 설립하고 2005년 첫 .NET 컴포넌트를 개발한 후, 마이크로소프트 생태계 전반에 걸쳐 복잡한 문제를 해결하는 데 전문성을 발휘해 왔습니다.

그의 대표 제품인 IronPDF 및 Iron Suite .NET 라이브러리는 전 세계적으로 3천만 건 이상의 NuGet 설치 수를 기록했으며, 그의 핵심 코드는 전 세계 개발자들이 사용하는 다양한 도구에 지속적으로 활용되고 있습니다. 25년의 실무 경험과 41년의 코딩 전문성을 바탕으로, 제이콥은 차세대 기술 리더들을 양성하는 동시에 기업 수준의 C#, Java, Python PDF 기술 혁신을 주도하는 데 주력하고 있습니다.

아이언 서포트 팀

저희는 주 5일, 24시간 온라인으로 운영합니다.
채팅
이메일
전화해