-2

I'm using c#. I have a string "1,2-Benzene-d4",36925,10.483,0.95,,

Expected string array is,

str[0] = "1,2-Benzene-d4"
str[1] = 36925
str[2] = 10.483
str[3] = 0.95
str[4] =  

I tried to achieve split using below function where mystring is input string delimiter is (,)

  public static string[] SplitDelimitedText(string myString, string delimiter, out int numberOfFields)
    {
        string strDelimiter = "\"" + delimiter;
        string[] strSeperator = null;
        //string[] arrayOfFields = new string[numberOfFields+1];
        List<string> arrayOfFields = new List<string>();
        try
        {
            if (!string.IsNullOrEmpty(myString))
            {
                if (myString.StartsWith("\""))
                {
                    strSeperator = new string[1];
                    strSeperator[0] = strDelimiter;
                }
                else
                {
                    strSeperator = new string[2];
                    strSeperator[0] = strDelimiter;
                    strSeperator[1] = delimiter;
                }

                string[] arrayOfSplitString = myString.Split(strSeperator, StringSplitOptions.None);
                arrayOfFields.Add("");
                for (int iCount = 0; iCount < arrayOfSplitString.Length; iCount++)
                {
                    arrayOfFields.Add(arrayOfSplitString[iCount].Replace("\"", "").Trim());                       
                }
                numberOfFields = arrayOfSplitString.Length;
            }
            else
                numberOfFields = 0;
        }
        catch
        {
            throw;
        }
        return arrayOfFields.ToArray();
    }
Kiran Desai
  • 1,711
  • 2
  • 19
  • 37
  • 1
    It look like a [CSV](https://en.wikipedia.org/wiki/Comma-separated_values). Perhaps you want to use existing tool dealing with CSv before hand crafting you own parser and having to handle Quoted string, et type conversion. Some thing like [CSV Helper](https://joshclose.github.io/CsvHelper/) will be able to deal with your exmepl in 10 line of code. Ps Im not affiliated just pointing to a tool I use. – xdtTransform Aug 30 '19 at 14:15
  • @Kiran , If you had to use inteligible name for str[0] .. str[5] . What will it be? – xdtTransform Aug 30 '19 at 14:19
  • 2
    @ed-plunkett The question is wrongly closed as a duplicate. The link points to a different question. – Angel Aug 30 '19 at 14:49
  • @Kiran Use regular expressions. It would be easier – Angel Aug 30 '19 at 14:52
  • @Angel Ahh, the comma in the quoted value. He needs [a CSV parser](https://stackoverflow.com/a/3508572/424129), not a regular expression. Thanks for catching that. – 15ee8f99-57ff-4f92-890c-b56153 Aug 30 '19 at 14:53
  • @ed-plunkett The string he wants to separate has the complexity of containing a comma inside double quotes – Angel Aug 30 '19 at 14:54
  • 1
    @KiranDesai Unless there are further complications in the format that you haven't mentioned, [what you're looking for is a CSV parser](https://stackoverflow.com/a/3508572/424129). This could be done with a regex, but you're usually just borrowing trouble if you use a regex to parse an established format with available parsers. – 15ee8f99-57ff-4f92-890c-b56153 Aug 30 '19 at 14:56

2 Answers2

1

As ed replied in the comment you can use the TextFieldParser class by passing the string in the constructor.

Another way would be to use regular expressions to solve it. Here is an example:

String inputStr = "\"1,2 - Benzene - d4\",36925,10.483,0.95,,";
String pattern = "\"[^\"]*\"|[^,]+";
Regex regex = new Regex(pattern);
Match match = regex.Match(inputStr);
while (match.Success)
{
    Console.WriteLine("Found: {0}", match.Groups[0].Value);
    match = match.NextMatch();
}
Angel
  • 3,617
  • 1
  • 16
  • 13
1

Regex is the way to go. Try this NetFiddle

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
            var input ="\"1,2-Benzene-d4\",36925,10.483,0.95,,";
            //Define pattern
            Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

            //Separating columns to array
            string[] X = CSVParser.Split(input);

            for (int i=0;i<X.Length;i++)
                Console.WriteLine("{0}: {1}\n",i,X[i]);
    }
}
fededim
  • 429
  • 5
  • 12