views:

99

answers:

3
+1  Q: 

Split string var

Hi, I have a question:

Let's say I have this string var:

string strData = "1|2|3|4||a|b|c|d"

Then, I make a Split:

string[] strNumbers = strData.Split("||"); //something like this, I know It's not this simple

I need two separate parts, each one containing this:

//strNumbers -> {"1","2","3","4"},{"a","b","c","d"}

So that after that, I could do this:

string[] strNumArray = strNumbers[0].Split('|');
//strNumArray -> '1', '2', '3', '4'

And same with the other part (letters).

Is it possible? to make this double split with the same character, but the first time the character is repeated twice?.

Thanks.

PD. I'm using C#.

+5  A: 

It'll work fine, your syntax is just off.

So first, your declarations are off. You want the [] on the type, not the name.

Second, on String.Split, there is an overload that takes in a string array and a StringSplitOptions. Just trying to do "||" will call the param char overload, which is invalid.

So try this:

string strData = "1|2|3|4||a|b|c|d";
string[] strNumbers = strData.Split(new[] {"||"}, StringSplitOptions.None);
string[] strNumArray = strNumbers[0].Split('|');

You can change the StringSplitOptions to RemoveEmptyEntries if you wanted.

Brandon
Yeah, you are right about my declaration mistakes but that was only because of my hurry to type the question. I edited the question and correct the declarations to avoid missundertoods.
lidermin
You were right !! many thanks, I tried everything but: new[] {'||'} !! haha. Thanks again.
lidermin
A: 
    Dim s As String = "1|2|3|4|5|6|7||a|b|c|d|e|f"
    Dim nums() As String = s.Split(New String() {"||"}, StringSplitOptions.None)(0).Split("|")
    Dim strs() As String = s.Split(New String() {"||"}, StringSplitOptions.None)(1).Split("|")
Will Marcouiller
None of those Split calls are compilable. `"||"` won't match the `params char` overload, and you can't do a String.Split using a string unless you make it an array and pass in a StringSplitOption.
Brandon
Thanks! I was a bit distracted and revised it, though it is VBNET. =)
Will Marcouiller
A: 

in .net 3.5:

string strData = "1|2|3|4||a|b|c|d";  
var s1 = strData.Split(new string[] { "||" }, StringSplitOptions.None);
var numbers = s1[0].Split('|');
var letters = s1[1].Split('|');
StupidDeveloper