3

I have a string in C#. It's blank at the beginning, but eventually it will become something like

public string info12 = "0, 50, 120, 10";

One of you might be thinking, eh? Isn't than an integer array? Well it needs to stay a string for the time being, it must be a string.

How can I convert this string into an string array (Variable info13) so I can eventually reference it into more variables.

info 14 = info13[0];
info 15 = info13[1];

PLEASE NOTE: This is not a duplicate question. If you read the whole thing, I clearly stated that I have an array of strings not integers.

1
  • You can simply call the .Split('?,') method, so simple! Commented Aug 2, 2014 at 1:23

1 Answer 1

19

Here are a few options:

1. String.Split with char and String.Trim

Use string.Split and then trim the results to remove extra spaces.

public string[] info13 = info12.Split(',').Select(str => str.Trim()).ToArray();

Remember that Select needs using System.Linq;

2. String.Split with char array

No need for trim, although this method is not my favorite

public string[] info13 = info12.Split(new string[] { ", " }, StringSplitOptions.None);

3. Regex

public string[] info13 = Regex.Split(info12, ", ");

Which requires using System.Text.RegularExpressions;

EDIT: Because you no longer need to worry about spaces, you can simply do:

public string[] info13 = info12.Split(',');

Which will return a string array of the split items.

Sign up to request clarification or add additional context in comments.

8 Comments

My bad, there shouldn't be any spaces. But I do get this error a field initializer cannot reference the non-static field, method, or property gui.info12
You cannot access something that is not static, from a static method. Try making info12 static, provided that their is only one instance of it.
It's not static. The script changes the variable info 12 towards the beginning of the script.
static does not mean const, it can still be changed. You are trying to reference a non static object from a static method.
I changed info 12 to a static string. Now it says System.Array does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument.
|