Example: a - b - c must be split as a and b - c, instead of 3 substrings
-
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.AnthonyWJones– AnthonyWJones2009-06-16 11:27:29 +00:00Commented Jun 16, 2009 at 11:27
-
...but only 15 questions are tagged "question" ;)Guffa– Guffa2009-06-16 11:42:15 +00:00Commented Jun 16, 2009 at 11:42
Add a comment
|
7 Answers
Specify the maximum number of items that you want:
string[] splitted = text.Split(" - ", count: 2, StringSplitOptions.None);
2 Comments
Max Schilling
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!
Aimal Khan
Btw, the 2 in the answer represents the number of substrings to return!
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
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
Jamie Rees
This will give you an array with the following
[a,b,c] and not [a,b-c]. Plus wrong language.Gaurav Arora
Thanks @JamieR for quoting it. I corrected my answer.