Search code examples
c#arraysstringdelimiter

How to make a delimiter in c# and take the value


C# Visual Studio 17

Just assume I have a string which has the value [3-4+6*2] or even [3-4+20-0.5] ... and I want them to be stored in a string array... I've researched and found that using split, trim start, trim end We can separate them...

.TrimStart('[')
.TrimEnd(']')
.Split('-','*','+');

But I was unable to find whether we can do this I mean

But I couldn't find anywhere how to store the delimiters too but have them do their work(i meant separating)!!

The value stored will be { 3, 4, 6, 2 } but I want this { 3, -, 4, +, 6, *, 2 } and what do I do with the extraordinary zeroes!!!?


Solution

  • In general case, you have to use a parser; if want just to split and preserve the delimiter, please, have a look at Regex.Split:

      string source = "[-3*4+20-0.5/-4.1]";
    
      //TODO: specify the delimiters:
      // If you want more delimiters, e.g. (, ), [, ] etc. 
      // for, say, 9*[(456+789)/(95-2.96)-3]
      // just add them into the array
      char[] delimiters = new char[]  { '*', '+', '-', '/' };
    
      string pattern = "(" + string.Join("|", delimiters
        .Select(item => Regex.Escape(item.ToString()))) + ")";
    
      string[] result = Regex
        .Split(source.TrimStart('[').TrimEnd(']'), pattern) // (...) preserves delim
        .Select(item => item.Trim()) // <- if you want to trim each item 
        .Where(item => !string.IsNullOrEmpty(item))
        .ToArray();
    
      // -, 3, *, 4, +, 20, -, 0.5, /, -, 4.1
      Console.Write(string.Join(", ", result));
    

    Edit: For large texts you may want to implement the Split manually:

    public static List<string> SplitPreserveSeparators(string source, char[] delimiters) {
      if (null == source)
        throw new ArgumentNullException("source") 
      else if (delimiters == null)
        throw new ArgumentNullException("delimiters") 
    
      int start = 0;
      int index = -1;
    
      List<string> items = new List<string>();
    
      while ((index = source.IndexOfAny(delimiters, start)) >= 0) {
        string value = source.Substring(start, index - start);
    
        if (!string.IsNullOrEmpty(value))
          items.Add(value);
    
        items.Add(source.Substring(index, 1));
        start = index + 1;
      }
    
      if (start < source.Length)
        items.Add(source.Substring(start));
    
      return items;
    }
    

    And use it

    string source = "[-3-4+20-0.5/-4.1]";
    char[] delimiters = new char[]  { '*', '+', '-', '/' };
    
    List<string> result =  SplitPreserveSeparators(
      source.TrimStart('[').TrimEnd(']'),
      delimiters);
    
    Console.Write(string.Join(", ", result));