How to split a string into elements of a string array in C#?


Set the string you want to split.

string str = "Hello World!";

Use the split() method to split the string into separate elements.

string[] res = str.Split(' ');

The following is the complete code to split a string into elements of a string array in C#.

Example

 Live Demo

using System;
class Demo {
   static void Main() {
      string str = "Hello World!";
      string[] res = str.Split(' ');
      Console.WriteLine("Separate elements:");
      foreach (string words in res) {
         Console.WriteLine(words);
      }
   }
}

Output

Separate elements:
Hello
World!

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 23-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements