简体   繁体   中英

How to split this string in c#?

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!

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"

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);
}
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);
}

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

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.

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM