OneBite.Dev - Coding blog in a bite size

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.

  1. 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!";
  1. The function Split(' ') is called on the input string. In C#, the Split() 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(' ');
  1. This results in an array of strings, splitInput, where each element of the array is a substring of input separated by the delimiter.

  2. Lastly, we use a foreach loop to iterate through each element in the splitInput array. It prints out each word on a separate line by using Console.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.

c-sharp