Splits strings, but leaves anything within quotes - CSharp System

CSharp examples for System:String Split

Description

Splits strings, but leaves anything within quotes

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System;//from  ww w. ja  v  a  2 s  . c  om

public class Main{
        //Splits strings, but leaves anything within quotes
        //(Has issues with nested quotes
        //This is a "very long" string ->
        //This
        //is
        //a
        //very long
        //string
        public static string[] SplitQuotes(string input, bool ignoreQuotes, string separator)
        {
            if (ignoreQuotes)
                return input.Split(separator.ToCharArray());
            else
            {
                string[] words = input.Split(separator.ToCharArray());
                List<string> newWords = new List<string>();

                for (int i = 0; i < words.Length; i++)
                {
                    if (words[i].StartsWith('"'.ToString(CultureInfo.InvariantCulture)))
                    {
                        List<string> linked = new List<string>();
                        for (int y = i; y < words.Length; y++)
                        {
                            if (words[y].EndsWith('"'.ToString()))
                            {
                                linked.Add(words[y].Substring(0, words[y].Length - 1));
                                i = y;
                                break;
                            }
                            if (words[y].StartsWith('"'.ToString()))
                                linked.Add(words[y].Substring(1));
                        }
                        newWords.Add(String.Join(separator, linked.ToArray()));
                        linked.Clear();
                    }
                    else
                        newWords.Add(words[i]);
                }
                return newWords.ToArray();
            }
        }
}

Related Tutorials