113

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.

WerWet
  • 323
  • 5
  • 14
Vishnu Y
  • 2,211
  • 4
  • 25
  • 38

6 Answers6

263

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

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

Returns:

101
a,b,c,d
Bakudan
  • 19,134
  • 9
  • 53
  • 73
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
26
string s = "101,a,b,c,d";
int index = s.IndexOf(',');
string first =  s.Substring(0, index);
string second = s.Substring(index + 1);
Arin Ghazarian
  • 5,105
  • 3
  • 23
  • 21
  • 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 03 '14 at 04:25
  • @pcnThird, Don't know, though I think GrantWinney's answer is the best. – Arin Ghazarian Feb 03 '14 at 04: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 '17 at 08: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 09 '17 at 03:45
15

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.

Pierre-Luc Pineault
  • 8,993
  • 6
  • 40
  • 55
9

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.

dotNET
  • 33,414
  • 24
  • 162
  • 251
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);
Dilan
  • 2,610
  • 7
  • 23
  • 33
Sierra
  • 71
  • 3
1

In .net Core you can use the following;

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

Returns:

101
a,b,c,d
mark_h
  • 5,233
  • 4
  • 36
  • 52