Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Split only on first separator in C#?

Tags:

string

c#

.net

String.Split is convenient for splitting a string with in multiple part on a delimiter.

How should I go on splitting a string only on the first delimiter. E.g. I've a String

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

And I'd want an array looking like

{"Time","10:12:12\r\n"} 
like image 468
Anonym Avatar asked Jan 07 '10 11:01

Anonym


People also ask

How do you split a string only on the first instance of specified character?

Use the String. split() method with array destructuring to split a string only on the first occurrence of a character, e.g. const [first, ... rest] = str. split('-'); .

What is the default separator in split ()?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do I split a string on one space?

Use the str. split() method with maxsplit set to 1 to split a string only on the first space, e.g. my_str. split(' ', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .


2 Answers

The best approach depends a little on how flexible you want the parsing to be, with regard to possible extra spaces and such. Check the exact format specifications to see what you need.

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

Will limit you two 2 substrings. However, this does not trim the space at the beginning of the second string. You could do that in a second operation after the split however.

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

Should work, but will break if you're trying to split a header name that contains a space.

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

Will do exactly what you describe, but actually requires the space to be present.

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

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

To keep the format somewhat flexible, and your code readable, I suggest using the first option:

string[] split = yourString.Split(new char[] { ':' }, 2); // Optionally check split.Length here split[1] = split[1].TrimStart(); 
like image 70
Thorarin Avatar answered Oct 08 '22 22:10

Thorarin


In your example above you could split on ": " (i.e. colon with trailing space) as this appears to be what you've done. If you really did split on just the first delimeter you'd see a leading space in your second array element.

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

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

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

... which allows you to specify a max number of substrings.

like image 43
Martin Peck Avatar answered Oct 08 '22 22:10

Martin Peck