Saturday, 2 July 2016

Split string with string in C# Code

C# Split A String By Another String.
How do I split a string by a multi-character delimiter in C#?


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

namespace Split_By_Sting
{
    class Program
    {
        static void Main(string[] args)
        {

            string input = "\"Raj\",\"new delhi, 110092\",\"developer\"";
            Console.WriteLine(input);

            #region using regex & split
            Console.WriteLine("Using regex & split-------------------------");
            string pattern = @"""\s*,\s*"""; //@"""*,*"""; //@""","""
            Console.WriteLine(pattern);
            // input.Substring(1, input.Length - 2) removes the first and last " from the string
            string[] tokens =  Regex.Split( input.Substring(1, input.Length - 2), pattern);
            foreach (var item in tokens)
            {
                Console.WriteLine(item);
            }
            #endregion


            #region using split function
            Console.WriteLine("Using Split Function Only---------------------");
            string[] arr = input.Substring(1, input.Length - 2).Split(new string[] { @""",""" }, StringSplitOptions.None);
            foreach (var item in arr)
            {
                Console.WriteLine(item);
            }
            #endregion 

            Console.Read();
        }
    }
}