Split A String By Empty Space In C#
Code snippet for how to Split A String By Empty Space In C# with sample and detail explanation
Manipulating strings is a common task in any programming language and C# is no exception. This article will demonstrate how to split a string by empty space in C# in an easy-to-follow manner.
Code snippet: Splitting a String by Empty Space in C#
Here’s a code snippet you can use to split a string by empty space in C#:
string input = "Hello World!";
string[] splitInput = input.Split(' ');
foreach(string str in splitInput)
{
Console.WriteLine(str);
}
This code would output:
Hello
World!
Code Explanation: Splitting a String by Empty Space in C#
Let’s break down the code snippet step by step.
- Firstly, we declare a string variable
input
that contains the text we want to split, which in this case is “Hello World!“.
string input = "Hello World!";
- The function
Split(' ')
is called on theinput
string. In C#, theSplit()
function breaks a string into parts based on a delimiter, which is specified as a parameter. Here, the delimiter is an empty space (’ ’).
string[] splitInput = input.Split(' ');
-
This results in an array of strings,
splitInput
, where each element of the array is a substring ofinput
separated by the delimiter. -
Lastly, we use a
foreach
loop to iterate through each element in thesplitInput
array. It prints out each word on a separate line by usingConsole.WriteLine(str)
within the loop body.
foreach(string str in splitInput)
{
Console.WriteLine(str);
}
This is a simple yet powerful way to split a string by spaces in C#. Understanding how to manipulate and handle strings is a crucial aspect of many more complex tasks in programming. Keep practicing and exploring more features of the string class in C# to solidify your knowledge.