tags:

views:

459

answers:

7

hi i'm really not used to the split string method in c# and i was wondering how come there's no split by more than one char function?

and my attempt to try to split this string below using regex has just ended up in frustration. anybody can help me?

basically i want to split the string below down to

aa**aa**bb**dd^__^a2a**a2a**b2b**dd^__^

into

aa**aa**bb**dd
a2a**a2a**b2b**dd

and then later into

aa
aa
bb
dd

a2a
a2a
b2b
dd

thanks!

+10  A: 

You can split using a string[]. There are several overloads.

string[] splitBy = new string[] {"^__^"};
string[] result = "aa*aa*bb*dd^__^a2a*a2a*b2b*dd^__^".Split(splitBy, StringSplitOptions.None);

// result[0] = "aa*aa*bb*dd", result[1] = "a2a*a2a*b2b*dd"
Oded
+7  A: 

You're looking for this overload:

someString.Split(new string[] { "^__^" }, StringSplitOptions.None);

I've never understood why there isn't a String.Split(params string[] separators).
However, you can write it as an extension method:

public static string[] Split(this string str, params string[] separators) {
    return str.Split(separators, StringSplitOptions.None);
}
SLaks
+2  A: 
var split = @"aa**aa**bb**dd^__^a2a**a2a**b2b**dd^__^".Split(new string[] {"^__^"}, StringSplitOptions.RemoveEmptyEntries);

foreach(var s in split){
   var split2 = s.Split(new string[] {"**"}, StringSplitOptions.RemoveEmptyEntries);
}
sashaeve
A: 

How about one of these:

string.Join("**",yourString.Split("^__")).Split("**")
yourString.Replace("^__","**").Split("**")

You will have to check the last item, in your example it would be an empty string.

Sergio
This won't compile.
SLaks
A: 

As already stated, you can pass in a string array to the Split method. Here's how the code might look based on your recent edits to the quesiton:

string x = "aa**aa**bb**dd^__^a2a**a2a**b2b**dd^__^";
string[] y =  x.Split(new string[]{"^__^"},StringSplitOptions.None);
string[] z = y[0].Split(new string[]{"**"},StringSplitOptions.None);
Jamie Dixon
+1  A: 

This will give you an IEnumerable<IEnumerable<string>> containing the values you want.

string[] split1 = new[] { "^__^" };
string[] split2 = new[] { "**" };
StringSplitOptions op = StringSplitOptions.RemoveEmptyEntries;
var vals = s.Split(split1,op).Select(p => p.Split(split2,op).Cast<string>());

You can also throw some ToList()'s in there if you wanted List<List<string>> or ToArray()'s for a jagged array

juharr
A: 

The VB.NET Version that works.

Module Module1

Sub Main()
    Dim s As String = "aa**aa**bb**dd^__^a2a**a2a**b2b**dd^__^"
    Dim delimit As Char() = New Char() {"*"c, "^"c, "_"c}

    Dim split As String() = s.Split(delimit, StringSplitOptions.RemoveEmptyEntries)
    Dim c As Integer = 0
    For Each t As String In split
        c += 1
        Console.WriteLine(String.Format("{0}: {1}", c, t))
    Next

End Sub
Black Frog
This is not what he's trying to do.
SLaks