test_yuuzoo
test_yuuzoo

Reputation: 25

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

Upvotes: 0

Views: 1987

Answers (3)

Harsha
Harsha

Reputation: 1879

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

Upvotes: 1

Dan Tao
Dan Tao

Reputation: 128317

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

Upvotes: 5

markt
markt

Reputation: 5156

Use String.Split

Upvotes: 10

Related Questions