Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string that delimiters remain in the end of result?

I have several delimiters. For example {del1, del2, del3 }. Suppose I have text : Text1 del1 text2 del2 text3 del3

I want to split string in such way:

  1. Text1 del1
  2. text2 del2
  3. text3 del3

I need to get array of strings, when every element of array is texti deli. How can I do this in C# ?

like image 219
Aram Gevorgyan Avatar asked Dec 13 '25 01:12

Aram Gevorgyan


2 Answers

String.Split allows multiple split-delimeters. I don't know if that fits your question though.

Example :

    String text = "Test;Test1:Test2#Test3";
    var split = text.Split(';', ':', '#');
   //split contains an array of "Test", "Test1", "Test2", "Test3"

Edit: you can use a regex to keep the delimeters.

 String text = "Test;Test1:Test2#Test3";
 var split = Regex.Split(text, @"(?<=[;:#])");
 // contains "Test;", "Test1:", "Test2#","Test3"
like image 132
Alex Avatar answered Dec 14 '25 16:12

Alex


This should do the trick:

    const string input = "text1-text2;text3-text4-text5;text6--";
    const string matcher= "(-|;)";

    string[] substrings = Regex.Split(input, matcher); 

    StringBuilder builder = new StringBuilder();
    foreach (string entry in substrings)
    {
        builder.Append(entry);
    }

    Console.Out.WriteLine(builder.ToString());

note that you will receive empty strings in your substring array for the matches for the two '-';s at the end, you can choose to ignore or do what you like with those values.

like image 39
krystan honour Avatar answered Dec 14 '25 16:12

krystan honour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!