3

I would like to split string "203136;70;;;;;" by ;; separator but in this string separator was mixed with regular symbol ;

From "203136;70;;;;;"

To

  • 203136;70
  • ;
Snail
  • 57
  • 7
  • 1
    you mean `StringSplitOptions.RemoveEmptyEntries` ? - https://dotnetfiddle.net/YTR2KM – Rand Random Aug 22 '23 at 11:07
  • Does this answer your question? [C# Regex Split - commas outside quotes](https://stackoverflow.com/questions/3147836/c-sharp-regex-split-commas-outside-quotes) – T1Space Aug 22 '23 at 11:08
  • @T1Space I don't know if it will help. I've never used a Regex, have no idea how to use it. I hoped that there exists some easier solution. – Snail Aug 24 '23 at 13:07

2 Answers2

2

You can use StringSplitOptions.RemoveEmptyEntries:

using System;

class Program
{
    static void Main()
    {
        string input = "203136;70;;;;;";
        string[] result = input.Split(new string[] { ";;" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string r in result)
        {
            Console.WriteLine(r);
        }
    }
}
203136;70
;
NoName
  • 643
  • 3
  • 8
  • `new string[] { ";;" }` - my eyes they hurt, .net framework code so bad :) | FYI: overload `Split(String, StringSplitOptions)` got introduced in .net core 2.0 released August 14, 2017 - has it really been already 6 years, damn... – Rand Random Aug 22 '23 at 11:20
  • I tried your code but it will not work as I want when I am trying to make text more complicated I mean add some more `;`. I decided to did it with my own method. – Snail Aug 24 '23 at 13:09
-3
string[] SplitValuesLine(string line)
    {
        var list = new List<string>();
        var charArray = line.ToCharArray();
        var builder = new StringBuilder();
        var valueReached = false;
        for (int i = 0; i < charArray.Length; i++)
        {
            if (valueReached && (i + 1) < charArray.Length && charArray[i] == charArray[i + 1] && charArray[i] == ';')
            {
                list.Add(builder.ToString());
                builder.Clear();
                valueReached = false;
                i++;
            }
            else
            {
                builder.Append(charArray[i]);
                valueReached = true;
            }
        }
        return list.ToArray();
    }

This not elegant solution helped me, cause the StringSplitOptions.RemoveEmptyEntries removes some strings which I would like to have.

Snail
  • 57
  • 7