跳過到頁腳內容
.NET幫助

C# 分割字串(開發者的工作原理)

無論您是編程新手還是一位新興的 C# 開發人員,了解如何拆分字符串是一項能大大提升您編碼能力的基本技能。 在本教程中,我們將深入探討 C# 中的拆分操作。

字符串拆分簡介

在編程中,字符串是一系列字符,有時會出現需要根據特定的分隔符或界定符將其拆分成較小部分的情況。 這一過程稱為字符串拆分,是處理文本數據時的重要技術。 想像您有一句話,您希望將其分隔為單個單詞——這是字符串拆分的一個典型例子。

在 C# 中,String.Split() 是您這項任務的理想工具。 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,您希望使用分號和空格作為分隔符來拆分它。

要實現這一點,您可以使用帶有 params char 參數的 string.Split() 方法:

// 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

這將產生一個包含三個元素的數組:applebananaorange

限制子字符串的數量

在某些情況下,您可能希望將字符串拆分為有限數量的子字符串。 這在處理長字符串或當您只對特定數量的片段感興趣時很有用。 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 時,結果數組將包含 。 字符串的其餘部分(四,五)保持不變。

創建您自己的字符串拆分擴展

雖然內置的 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

在這個例子中,我們定義了一個名為 SplitBySubstring 的擴展,它接受子字符串分隔符作為輸入並使用給定的分隔符應用內置的 String.Split() 方法。 這種方法擴展了 C# 的 string 類的功能,同時保持您的代碼組織良好且可重用。

Iron Suite: 為 C# 提供強大功能的庫集合

Iron Suite 是一套全面的工具集,旨在為 C# 開發人員提供多領域高級功能。 從文檔處理到光學字符識別(OCR),這些庫是現代開發工具包中不可或缺的一部分。 有趣的是,這些庫可以與 C# 的 String.Split() 方法關聯,這是 C# 中基本的字符串操作功能。

IronPDF: 將 HTML 轉換為 PDF

IronPDF 允許開發人員直接在 .NET 應用程序中將 HTML 渲染為 PDF。 這個強大的庫幫助創建、編輯甚至提取 PDF 內容。 它提供了一個直觀的 API,使 PDF 操作如同執行字符串操作(如拆分字符串)一樣簡單。 For further information, tutorials, and guidance on using IronPDF, visit IronPDF's website and the HTML to PDF tutorial.

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:精通 Excel 操作

在 C# 應用程序中處理 Excel 文件時,IronXL 是首選庫。 它允許開發人員輕鬆讀取、編輯和操作 Excel 文件,類似於通過 C# 處理字符串操作。

IronOCR: 光學字符識別

IronOCR 是開發人員在應用程序中集成 OCR 功能的基本庫。 通過利用 IronOCR,您可以從圖像和掃描文檔中讀取文本,將它們轉換為易於管理的字符串,類似於使用 C# 分割字符串時的操作。 瞭解有關 IronOCR 的更多信息以及如何將其集成到您的項目中,請訪問 IronOCR 網站

IronBarcode: 條碼掃描和生成

最後,Iron Suite 包括 IronBarcode,它是 C# 應用程序中條碼讀取和生成的綜合解決方案。 這個庫將條碼操作的複雜性降低到了類似於 C# 字符串操作的水平。

結論

Iron Suite 及其各個組件 IronPDF、IronXL、IronOCR 和 IronBarcode 為開發人員提供了使用 PDF、Excel 文件、OCR 和條形碼的簡單解決方案。 通過簡化複雜操作,正如 C# 拆分字符串方法簡化字符串操作一樣,這些庫是現代開發人員的絕佳工具。

這些不可思議的產品中的每一個都提供 免費試用,以便完整地探索和試驗其功能。 每款產品的授權從 liteLicense 開始,提供了進階功能的實惠途徑。

只需購買兩個單獨產品的價格即可購得完整的 Iron Suite 套件。 此捆綁優惠不僅擴展了開發工具包的功能,還代表了極佳的價值。

常見問題解答

String.Split() 方法在 C# 中是如何運作的?

C# 中的 String.Split() 方法根據指定的分隔符字元將字串分割成子字串的陣列。這對於有效解析和管理字串資料非常有用。

有哪些進階方法可以在 C# 中分割字串?

C# 中的進階字串分割可以包含使用多個分隔符、使用 StringSplitOptions.RemoveEmptyEntries 移除空項,以及在 Split 方法中增加一個參數限制子字串的數量。

我可以在 C# 中創建一個自定義方法來分割字串嗎?

可以,您可以定義擴充方法來創建自定義的字串分割功能。例如,您可以使用 SplitBySubstring 擴充方法根據特定子字串而不是單個字元來分割字串。

什麼是 C# 開發人員的 Iron Suite?

Iron Suite 是一組強大的程式庫集合,旨在增強 C# 的開發。它包括像 IronPDF 這樣的工具,用於 PDF 操作、IronXL 用於 Excel 操作、IronOCR 用於光學字元識別、以及 IronBarcode 用於條碼生成。

如何在 C# 應用程式中將 HTML 轉換為 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF。此外,您可以使用 RenderHtmlFileAsPdf 方法將 HTML 文件轉換為 PDF。

IronOCR 為 C# 應用程式提供了哪些功能?

IronOCR 允許將光學字元識別集成到 C# 應用程式中,使從圖像和掃描的文件中讀取和轉換文本為可編輯和可管理的字串成為可能。

Iron Suite 的授權選擇有哪些?

Iron Suite 為每個產品提供免費試用,授權從 'liteLicense' 開始。一個完整套件包的價格相當於兩個單獨產品的價格,為開發人員提供極具價值的選擇。

IronPDF 如何簡化 .NET 中的 PDF 操作?

IronPDF 提供了一個直觀的 API,用於在 .NET 應用程式中創建、編輯和提取 PDF 的內容,使開發人員能夠輕鬆和高效地操作 PDF。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。