-5

I have this string:

   string var = "x1,x2,x3,x4";

I want to get x1, x2, x3, x4 separately in four different strings.

horgh
  • 17,918
  • 22
  • 68
  • 123

4 Answers4

3

This is a basic split

string yourString = "x1,x2,x3,x4";
string[] parts = yourString.Split(',');

foreach(string s in parts)
    Console.WriteLine(s);

I renamed the original variable into yourString. While it seems that it is accepted in LinqPad as a valid identifier I think that it is very confusing using this name because is reserved

Steve
  • 213,761
  • 22
  • 232
  • 286
2

Split it up.

var tokens = someString.Split(',');

Now you can access them by their index:

var firstWord = tokens[0];
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • 1
    Yes a very bad idea calling a variable var, however it seems that it is accepted (at least in LinqPad) – Steve Dec 17 '13 at 00:57
  • 1
    Well I'll be damned. Appearantly `var` is considered a [contextual keyword](http://msdn.microsoft.com/en-us/library/x53a06bb.aspx) and from a few tests those seem to be allowed as variable names in both LINQPad and VS. – Jeroen Vannevel Dec 17 '13 at 01:00
1

String.Split

var foo = "x1,x2,x3,x4";
var result = foo.Split(',');

There's also the "opposite: String.Join

Console.WriteLine(String.Join('*', result));

Will output: x1*x2*x3*x3

RobIII
  • 8,488
  • 2
  • 43
  • 93
0

To separate values with comma between them, you can use String.Split() function.

string[] words = var.Split(',');
foreach (string word in words)
{
    Console.WriteLine(word);
}
Gabriel GM
  • 6,391
  • 2
  • 31
  • 34