TestString 2 <^> Test String3 What I want to bre...">

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 "<^>"?

+4
source share
3 answers

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); 
+14
source

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[]{'<', '^', '>'} 
+2
source

Try another overloaded Split method:

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

So, in your case, it might look like this:

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

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1306689/


All Articles