Split a string by deliminator - CSharp System

CSharp examples for System:String Split

Description

Split a string by deliminator

Demo Code


using System.Collections;
using System.Text;
using System;/*from  w w  w .j a va  2  s  .  c  om*/

public class Main{
        /// <summary>
        /// Split a string by deliminator
        /// </summary>
        /// <param name="source"></param>
        /// <param name="deliminator"></param>
        /// <returns></returns>
        public static string[] SplitComponents(string source, char deliminator)
        {
            int iStart = 0;
            string[] ret = null;
            string[] tmp;
            int i;
            string s;

            while (true)
            {
                // Find deliminator
                i = source.IndexOf(deliminator, iStart);

                if (InQuotes(source, i))
                    iStart = i + 1;
                else
                {
                    // Separate value
                    if (i < 0)
                        s = source;
                    else
                    {
                        s = source.Substring(0, i).Trim();
                        source = source.Substring(i + 1);
                    }

                    // Add value
                    if (ret == null)
                        ret = new string[] { s };
                    else
                    {
                        tmp = new string[ret.Length + 1];
                        Array.Copy(ret, tmp, ret.Length);
                        tmp[tmp.Length - 1] = s;
                        ret = tmp;
                    }

                    iStart = 0;
                }

                // Break on last value
                if (i < 0 || source == string.Empty)
                    break;
            }

            return ret;
        }
}

Related Tutorials