106

How can I split a C# string based on the first occurrence of the specified character? Suppose I have a string with value:

101,a,b,c,d

I want to split it as

101
a,b,c,d

That is by the first occurrence of comma character.

0

6 Answers 6

249

You can specify how many substrings to return using string.Split:

var pieces = myString.Split(new[] { ',' }, 2);

Returns:

101
a,b,c,d
0
25
string s = "101,a,b,c,d";
int index = s.IndexOf(',');
string first =  s.Substring(0, index);
string second = s.Substring(index + 1);
4
  • 5
    @pcnThird I didn't downvote but is probably because it is just code with no explanation of the method being used.
    – Mark Hall
    Feb 3, 2014 at 4:25
  • @pcnThird, Don't know, though I think GrantWinney's answer is the best. Feb 3, 2014 at 4:26
  • Actually, this one provides a fine alternative to the GrantWinney's answer for those not having access to this split method. (Those using the compact framework for exemple)
    – Maniz
    May 17, 2017 at 8:38
  • 5
    Maybe because if IndexOf can't find the delimiter it returns -1. In this case, the code will not correctly split the string. It should return the entire string as first, but first will be empty (or possibly crash).
    – ThisGuy
    Sep 9, 2017 at 3:45
13

You can use Substring to get both parts separately.

First, you use IndexOf to get the position of the first comma, then you split it :

string input = "101,a,b,c,d";
int firstCommaIndex = input.IndexOf(',');

string firstPart = input.Substring(0, firstCommaIndex); //101
string secondPart = input.Substring(firstCommaIndex + 1); //a,b,c,d

On the second part, the +1 is to avoid including the comma.

1
  • 2
    Don't use this; firstCommaIndex can be -1 if the comma was never found. Jun 27, 2018 at 14:33
8

Use string.Split() function. It takes the max. number of chunks it will create. Say you have a string "abc,def,ghi" and you call Split() on it with count parameter set to 2, it will create two chunks "abc" and "def,ghi". Make sure you call it like string.Split(new[] {','}, 2), so the C# doesn't confuse it with the other overload.

1
  • but see @sierra 's answer below
    – Fattie
    Jul 1, 2020 at 16:31
3
var pieces = myString.Split(',', 2);

This won't work. The overload will not match and the compiler will reject it.

So it Must be:

char[] chDelimiter = {','};
var pieces = myString.Split(chDelimiter, 2);
2

In .net Core you can use the following;

var pieces = myString.Split(',', 2);

Returns:

101
a,b,c,d
1
  • 3
    Split(',', 2) triggers a warning, with Visual Studio asking to cast 2 to char.
    – Cœur
    Aug 29, 2019 at 3:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.