18

Example: a - b - c must be split as a and b - c, instead of 3 substrings

2
  • Its amazing 1000+ questions tagged "programming" I just had to go find out how many quesitons were tagged "question" and there are some!! @Jon: FYI, SO is always about programming, non programming questions will very quickly get voted closed. Commented Jun 16, 2009 at 11:27
  • ...but only 15 questions are tagged "question" ;) Commented Jun 16, 2009 at 11:42

7 Answers 7

36

Specify the maximum number of items that you want:

string[] splitted = text.Split(" - ", count: 2, StringSplitOptions.None);
Sign up to request clarification or add additional context in comments.

2 Comments

I personally would have gone with "splat" for the array variable name... if you gonna make up a word, I say go for the gusto!
Btw, the 2 in the answer represents the number of substrings to return!
17
string s = "a - b - c";
string[] parts = s.Split('-', count: 2);
// note, you'll still need to trim off any whitespace

Comments

5
"a-b-c".Split( new char[] { '-' }, 2 );

Comments

2

You could use indexOf() to find the first instance of the character you want to split with, then substring() to get the two aspects. For example...

int pos = myString.IndexOf('-');
string first = myString.Substring(0, pos);
string second = myString.Substring(pos);

This is a rough example - you'll need to play with it if you don't want the separator character in there - but you should get the idea from this.

Comments

1
string[] splitted = "a - b - c".Split(new char[]{' ', '-'}, 2, StringSplitOptions.RemoveEmptyEntries);

Comments

0
var str = "a-b-c";
int splitPos = str.IndexOf('-');
string[] split = { str.Remove(splitPos), str.Substring(splitPos + 1) };

Comments

0

I have joined late and many of above answers are matched with my following words:

string has its own

Split

You can use the same to find the solution of your problem, following is the example as per your issue:

using System;

public class Program
{
    public static void Main()
    {
        var PrimaryString = "a - b - c";
        var strPrimary  = PrimaryString.Split( new char[] { '-' }, 2 );
        Console.WriteLine("First:{0}, Second:{1}",strPrimary[0],strPrimary[1]);

    }
}

Output:
First:a , Second: b - c

2 Comments

This will give you an array with the following [a,b,c] and not [a,b-c]. Plus wrong language.
Thanks @JamieR for quoting it. I corrected my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.