views:

85

answers:

5

So I've a string:

string x = "DR\nDC\nDD";

I want to get each line in a separated variable like this:

string y1 = "DR";
String y2 = "DC";
String y3 = "DD";

How can I do that?.

+4  A: 
String.Split('\n')

which will give you an array of strings.

Bryan
+6  A: 

Use String's split method.

string[] values = x.Split("\n");

And then if you really want them in 3 separate variables... :

string y1 = values[0];
string y2 = values[1];
string y3 = values[2];

But I would suggest leaving it in an array and processing from there.

froadie
The Split method also takes a second parameter of type StringSplitOptions. You can use the StringSplitOptions.RemoveEmptyEntries to eliminate blank entries from your array (for example, if your input string was something like "DR\nDC\nDD\n\n\nDE\n").
TLiebe
Thanks, but I've one more thing. I get an error when I send less than 3 variables indicating "Index was outside the bound of array", cause if I sent somthing like "DC\nRC" values[2] will result in such an error. How to avoid that?
DanSogaard
@DanSogaard - that would be the reason to leave it in the array rather than store it in 3 variables - it leaves it open to be any number of strings rather than limiting it to 3. And what if you would have more than 3? You would be ignoring any past the third. What are you doing with the values y1, y2, and y3? If it's the same thing, just loop through the array.
froadie
Well, I'm sending these values to be printed in a barcode label printer, so I won't need more than 3 lines, otherwise would be outsidee the bound of the label, which can't happen physically I mean. But problem is when Items are less than 3, which is most likely to be happen. I was thinking if there anyway I can check the number of values in the array so that in case of less than 3 I can assign y3 to null.
DanSogaard
So then you can just hardcode it as a conditional statement. if(values.length > 2){ do something with values[2] }, or something similar. And if there can be just 1 item, you'll have to do that check before doing anything with values[1] also. But if you're sending them all to be printed the same way anyway, just use a loop, it's cleaner. for(int i = 0; i < values.length; i++){ sendToPrinter values[i] }
froadie
Done, thank you so much, it's working as it should now :)
DanSogaard
+2  A: 

Use String.Split like this:

var arr = x.Split('\n');

string y1 = arr[0];
string y2 = arr[1];
string y3 = arr[2];
Nick Craver
+2  A: 
foreach (string yN in x.Split('\n'))
{
    // do something with yN
}

or

string[] yN = x.Split('\n');

string y1 = yN[0];
string y2 = yN[1];
string y3 = yN[2];
Nick Allen - Tungle139
A: 

You could find the index of '\' and parse based on that.

Icono123