Home > Software engineering >  Split String with multiple delimiters to different arrays in c#
Split String with multiple delimiters to different arrays in c#

Time:04-14

So I have a text file copied into memory that is delimited as follows:

"425,9856\n852,9658\n"

This is a long string with some 30,000 entries in total. What I want to do is create two arrays, one for the value to the left of the comma, one for the value to the right of the comma, and then to each array respectively i want to append the next two comma delimited strings that come after the "\n".

I have tried splitting using .Split and passing two delimiting values, but it obviously just creates one array with all values sequentially. Such as:

425 9856 852 9658

When what I want is:

array1: 452 852

array2: 9856 9658

Does that make sense? many thanks

CodePudding user response:

Since you're reading from a file, why not stream the input line-by-line, rather than reading the whole lot into memory in one go?

using var reader = new StreamReader(filePath);
while (reader.ReadLine() is not null line)
{
    // Each line is of the form '425,9856', so just split on the comma
    var parts = line.Split(',');
    firstList.Add(parts[0]);
    secondList.Add(parts[1]);
}

CodePudding user response:

You can just split it twice to get what you want

    public static void Main()
    {
        var foo = "425,9856"   Environment.NewLine   "852,9658"   Environment.NewLine;
        var array1 = new List<string>();
        var array2 = new List<string>();
        
        string[] lines = foo.Split(    
            new string[] { Environment.NewLine },    
            StringSplitOptions.None);
        
        foreach(var line in lines)
        {
            //Console.WriteLine("line: "   line);
            var lineSplit = line.Split(',');
            //Console.WriteLine("lineSplit: "   lineSplit.Length);
            //lineSplit.Dump();
            if(lineSplit.Length > 1)
            {
                array1.Add(lineSplit[0]);
                array2.Add(lineSplit[1]);
            }
        }
        Console.WriteLine("Array1: ");
        array1.Dump();
        Console.WriteLine("Array2: ");
        array2.Dump();
        
    }

And here's a working fiddle of it.

CodePudding user response:

You can use RegEx

string row = @"425,9856\n852,9658\n";

string left = @"[^|(?<=n)]\d*(?=,)";
string right = @"(?<=,)\d*(?=\\)";

Regex rgLeft = new Regex(left);
var l = rgLeft.Matches(row).Select(p=> p.Value);


Regex rgRight = new Regex(right);
var r = rgRight.Matches(row).Select(p=> p.Value);
  • Related