4

I have a string in following format

"TestString 1 <^> TestString 2 <^> Test String3

Which i want to split by "<^>" string.

Using following statement it gives the output i want

"TestString 1 <^> TestString 2 <^> Test String3"
 .Split("<^>".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)

But if my string contains "<" , ">" or "^" anywhere in the text then above split statement will consider that as well

Any idea how to split only for "<^>" string ?

3 Answers 3

14

By using ToCharArray you are saying "split on any of these characters"; to split on the sequence "<^>" you must use the overload that accepts a string[]:

string[] parts = yourValue.Split(new string[]{"<^>"}, StringSplitOptions.None);

Or in C# 3:

string[] parts = yourValue.Split(new[]{"<^>"}, StringSplitOptions.None);
Sign up to request clarification or add additional context in comments.

3 Comments

String3? I just started to search for a new unknown class. A typo though, right? :)
@Benjamin - I misread it as the source variable name (the formatting could be clearer...). Clarified as yourValue - better?
Of course. +1 from me anyway, going with Regex.Split was stupid in the first place..
2

Edit: As others pointed already out: String.Split has a good overload for your usecase. The answer below is still correct (as in working), but - not the way to go.


That's because this string.Split overload takes an array of separator chars. Each of them splits the string.

You want: Regex.Split

Regex regex = new Regex(@"<\^>");
string[] substrings = regex.Split("TestString 1 <^> TestString 2 <^>  Test String3");

And - a sidenote:

"<^>".ToCharArray()

is really just a fancy way to say

new[]{'<', '^', '>'}

4 Comments

You don't really need a regex here, but you should escape the start-of-string sign: <\^>.
@Kobi: Thanks. I didn't actually expect that and thought I only need to escape ^ in character groups. Tried it and you're obviously correct. Fixed the post.
Quite the opposite - character groups is the one place you normally don't have to escape characters.
@Kobi: But ^ is starting a negative character group - so I thought of that usage and somehow assumed that it won't act as anchor in the middle of the text. My bad. Thanks again.
1

Try another overloaded Split method:

public string[] Split(
    string[] separator,
    StringSplitOptions options
)

So in you case it may looks like:

var result = 
    yourString.Split(new string[] {"<^>"},StringSplitOptions.RemoveEmptyEntries);

Hope, this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.