How to split a line to another line?
I have a line in the following format
"TestString 1 <^> TestString 2 <^> Test String3
What I want to break down the line "<^>".
Using the following statement, it gives the output I want
"TestString 1 <^> TestString 2 <^> Test String3" .Split("<^>".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) But if my line contains "<", ">" or "^" anywhere in the text, then the above split expression will treat it the same way
Any idea to split only on the string "<^>"?
Using ToCharArray , you say "splitting into any of these characters"; you must use the overload that takes string[] to split into the sequence "<^>" :
string[] parts = yourValue.Split(new string[]{"<^>"}, StringSplitOptions.None); Or in C # 3:
string[] parts = yourValue.Split(new[]{"<^>"}, StringSplitOptions.None); Edit: as others have already pointed out: String.Split has a good overload for your usecase. The answer below is still correct (as at work), but not the way to go.
This is because this string.Split variable takes an array of separator characters. Each of them breaks a line.
You want: Regex.Split
Regex regex = new Regex(@"<\^>"); string[] substrings = regex.Split("TestString 1 <^> TestString 2 <^> Test String3"); And - a side message:
"<^>".ToCharArray() really just a fancy way of saying
new[]{'<', '^', '>'}