C# - String.Split() Method with Example

String.Split() Method C#: Given a string and we have to split the string in multiple strings by separating it by the given delimiter.
[Last updated : March 20, 2023]

String.Split() Method

The String.Split() Method returns array of strings, and we pass separator (delimiter) in character format to split string. Separators may be ',' , ':' , '$' etc.

Syntax

String[] String.Split(char ch);

Example

Input string: Hello,friends,how,are,you?

If we separate string from comma (,) (it is also known as delimiter), 
result is given below...

Output:
Hello 
friends 
how 
are 
you?

C# program to demonstrate the example of String.Split() method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      int i = 0;
      String str1;
      String[] str2;

      Console.Write("Enter string : ");
      str1 = Console.ReadLine();

      str2 = str1.Split(',');

      Console.WriteLine("Separated strings are: ");

      for (i = 0; i < str2.Length; i++) {
        Console.WriteLine(str2[i] + "");
      }

    }
  }

}

Output

First run:
Enter string : Hello,friends,how,are,you? 
Separated strings are:
Hello 
friends 
how 
are 
you?

Second run:
Enter string : Hi there,how are you?
Separated strings are:
Hi there
how are you?

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.