2
votes

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# ?

5
Could you clarify what would be the expected output when splitting "Text1 del1 text2 del2 text3 del3"?Strillo
@Strillo I edit. Now it is clear ?Aram Gevorgyan

5 Answers

8
votes

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"
2
votes

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.

1
votes

You could use a regex. For a string like this "text1;text2|text3^" you could use this:

(.*;|.*\||.*\^)

Just add more alternative pattens for each delimiter.

1
votes

If you want to keep the delimiter when splitting the string you can use the following:

string[] delimiters = { "del1", "del2", "del3" };

string input = "text1del1text2del2text3del3";
string[] parts = input.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

for(int index = 0; index < parts.Length; index++)
{
    string part = parts[index];
    string temp = input.Substring(input.IndexOf(part) + part.Length);

    foreach (string delimter in delimiters)
    {
        if ( temp.IndexOf(delimter) == 0)
        {
            parts[index] += delimter;
            break;
        }
    }
}

parts will then be:

    [0] "text1del1" 
    [1] "text2del2" 
    [2] "text3del3" 
1
votes

As @Matt Burland suggested, use Regex

List<string> values = new List<string>();
string s = "abc123;def456-hijk,";

Regex r = new Regex(@"(.*;|.*-|.*,)");
foreach(Match m in r.Matches(s))
   values.Add(m.Value);