BreakHead
BreakHead

Reputation: 10672

Using String Split

I have a text

Category2,"Something with ,comma"

when I split this by ',' it should give me two string

but in actual it split string from every comma.

how can I achieve my expected result.

Thanx

Upvotes: 0

Views: 145

Answers (5)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

Try this:

public static class StringExtensions
{
    public static IEnumerable<string> SplitToSubstrings(this string str)
    {
        int startIndex = 0;
        bool isInQuotes = false;

        for (int index = 0; index < str.Length; index++ )
        {
            if (str[index] == '\"')
                isInQuotes = !isInQuotes;

            bool isStartOfNewSubstring = (!isInQuotes && str[index] == ',');                

            if (isStartOfNewSubstring)
            {
                yield return str.Substring(startIndex, index - startIndex).Trim();
                startIndex = index + 1;
            }
        }

        yield return str.Substring(startIndex).Trim();
    }
}

Usage is pretty simple:

foreach(var str in text.SplitToSubstrings())
    Console.WriteLine(str);

Upvotes: 0

msarchet
msarchet

Reputation: 15242

There are a number of things that you could be wanting to do here so I will address a few:

Split on the first comma

String text = text.Split(new char[] { ',' }, 2);

Split on every comma

String text = text.Split(new char[] {','});

Split on a comma not in "

var result = Regex.Split(samplestring, ",(?=(?:[^']*'[^']*')*[^']*$)"); 

Last one taken from C# Regex Split

Upvotes: 2

Stuart
Stuart

Reputation: 66882

String.Split works at the simplest, fastest level - so it splits the text on all of the delimiters you pass into it, and it has no concept of special rules like double-quotes.

If you need a CSV parser which understands double-quotes, then you can write your own or there are some excellent open source parsers available - e.g. http://www.codeproject.com/KB/database/CsvReader.aspx - this is one I've used in several projects and recommend.

Upvotes: 0

Guffa
Guffa

Reputation: 700830

Specify the maximum number of strings you want in the array:

string[] parts = text.Split(new char[] { ',' }, 2);

Upvotes: 1

Ahe
Ahe

Reputation: 2124

Just call variable.Split(new char[] { ',' }, 2). Complete documentation in MSDN.

Upvotes: 4

Related Questions