Mehdi Souregi
Mehdi Souregi

Reputation: 3265

Split a string by two strings

In Java you can easily do something like this :

String[] result = input.split("AAA|BBB");

Which means that if you have an input like this :

sssAAAvvvBBBuuu

the result will be like this :

sss
vvv
uuu

What is the best way to do this in c#, I know you can hardly split a string by another string in c# :

string[] result = input.Split(new string[] { "AAA" }, StringSplitOptions.None);

But how about splitting a string with two strings AAA and BBB ?

Upvotes: 1

Views: 487

Answers (5)

Ramgy Borja
Ramgy Borja

Reputation: 2458

Or you can just create a function and call

public static string[] SplitString(string input)
{
    return Regex.Split(input, "AAA|BBB");
}

foreach (string word in SplitString("sssAAAvvvBBBuuu"))
{
    ........
    ........
}

Output: sss
        vvv
        uuu

Upvotes: 0

Stanislav Jelezov
Stanislav Jelezov

Reputation: 1

You can use this:

string str = "sssAAAvvvBBBuuu";
string[] separators = {"AAA", "BBB" };
string[] result = str.Trim().Split(separators, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 0

SahadevSinh Dodiya
SahadevSinh Dodiya

Reputation: 101

Ans is Below

 string test = "sssAAAvvvBBBuuu";

 string[] list = test.Split(new string[] { "AAA", "BBB" }, StringSplitOptions.None);

i hope you git answers

Upvotes: 0

PinBack
PinBack

Reputation: 2554

You can use Regex:

string[] result = Regex.Split(input, "AAA|BBB");

Upvotes: 3

Andrey Korneyev
Andrey Korneyev

Reputation: 26846

Just add another delimiter in array:

string[] result = input.Split(new string[] { "AAA", "BBB" }, StringSplitOptions.None);

Upvotes: 14

Related Questions