简体   繁体   中英

How to split the string in C#?

Note:

string s="Error=0<BR>Message_Id=120830406<BR>"

What's the most elegant way to split a string in C#?

使用String.Split

Supposing you want to split on the <BR> elements:

string[] lines = s.Split(new[] { "<BR>" }, StringSplitOptions.None);

Note that this will strip out the <BR> elements themselves. If you want to include those, you can either use the Regex class or write your own method to do it (most likely using string.Substring ).

My advice in general is to be wary of using regular expressions, actually, as they can end up being rather incomprehensible. That said, here's how you might use them in this case:

string[] lines = Regex.Matches(s, ".*?<BR>")
    .Cast<Match>()
    .Select(m => m.Value)
    .ToArray();

Use Slit string and here is the code:

string s = "Error=0<BR>Message_Id=120830406<BR>";
string[] stringSeparators = new string[] { "<BR>" };
string[] result = s.Split(stringSeparators, StringSplitOptions.None);

Edit: Linq updated. Good example: http://msdn.microsoft.com/en-us/library/tabh47cf.aspx

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