String.Split only on first delimiter in C #?

String.Split is convenient for breaking a string into several parts on a separator.

How can I go to split the line only on the first delimiter. For example. I have a line

"Time: 10:12:12\r\n" 

And I would like the array to look like

 {"Time","10:12:12\r\n"} 
+67
string c #
Jan 07
source share
4 answers

The best approach depends a little on how flexible the parsing should be, with respect to possible additional spaces and the like. Check the exact format specifications to find out what you need.

 yourString.Split(new char[] { ':' }, 2) 

Limit you to two substrings. However, this does not clip the space at the beginning of the second line. You can do this in the second operation after the split.

 yourString.Split(new char[] { ':', ' ' }, 2, StringSplitOptions.RemoveEmptyEntries) 

Should work, but will be broken if you try to split the header name containing a space.

 yourString.Split(new string[] { ": " }, 2, StringSplitOptions.None); 

Will do what you describe, but actually requires space.

 yourString.Split(new string[] { ": ", ":" }, 2, StringSplitOptions.None); 

Makes space optional, but you still have to have TrimStart() in case of more than one space.

To make the format somewhat flexible and read your code, I suggest using the first option:

 string[] split = yourString.Split(new char[] { ':' }, 2); // Optionally check split.Length here split[1] = split[1].TrimStart(); 
+124
Jan 07 '10 at 11:11
source share

In the above example, you can divide by ":" (ie, a colon with a trailing space), as this is similar to what you did. If you really only divided by the first delimeter, you would see a leading place in your second array element.

However, you should probably look at this Split overload ...

http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx

 public string[] Split( char[] separator, int count ) 

... which allows you to specify the maximum number of substrings.

+12
Jan 07 '10 at 11:10
source share
 ?("Time: 10:12:12\r\n").Split(new char[] { ':', ' ' }, 2, StringSplitOptions.RemoveEmptyEntries) {Dimensions:[2]} [0]: "Time" [1]: "10:12:12\r\n" 

other parameters:

 ?("Time: 10:12:12\r\n").Split(new char[] { ':' }, 2) {Dimensions:[2]} [0]: "Time" [1]: " 10:12:12\r\n" ?("Time: 10:12:12\r\n").Split(new char[] { ':' }, 1) {Dimensions:[1]} [0]: "Time: 10:12:12\r\n" ?("Time: 10:12:12\r\n").Split(new char[] { ':' }, 3) {Dimensions:[3]} [0]: "Time" [1]: " 10" [2]: "12:12\r\n" 
+3
Jan 07 '10 at 11:13
source share

I accepted Thorarin's answer above, The following should be able to cope with your requirement, as well as trim the gaps.

 yourString.Split(new []{'-'},2).Select(s => s.Trim()) 
+1
Oct 10 '13 at 3:18
source share



All Articles