How to Split a String into an Array in C#

Splitting a string into an array of substrings is a common operation in C# programming, allowing you to parse and manipulate textual data efficiently. Whether you need to separate words in a sentence or tokenize a string based on a delimiter, C# provides convenient methods to accomplish this task. Let’s explore how to split a string into an array in C#.

Using the Split Method

The Split method in C# allows you to divide a string into substrings based on a specified delimiter and returns an array of strings containing the substrings. This method is versatile and can be used in various scenarios.

string sentence = "Hello, world! How are you?";
string[] words = sentence.Split(' '); 
foreach (string word in words) 
{ 
   Console.WriteLine(word); 
}

In this example, the Split method is used to split the sentence string into an array of words based on the space delimiter. Each word is then printed to the console.

Specifying Multiple Delimiters

You can also specify multiple delimiters for splitting a string by passing an array of characters or strings to the Split method. This allows you to tokenize the string based on different separators.

string data = "apple,banana;orange"; 
char[] delimiters = { ',', ';' }; 
string[] fruits = data.Split(delimiters); 
foreach (string fruit in fruits) 
{ 
   Console.WriteLine(fruit); 
}

In this example, the data string is split into an array of fruit names using both comma and semicolon as delimiters.

By leveraging the Split method effectively, you can tokenize strings and manipulate textual data according to your specific requirements in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *


Categories


Tag Cloud

.net algorithms angular api Array arrays async asynchronous basic-concepts big o blazor c# code components containers control-structures csharp data structures data types dictionaries docker dom dotnet exceptions Handling framework functions git guide javascript json leetcode linq lists loops methods MVC npm object oriented programming oop operators promisses sorted try catch typescript web framework