get variables in between commas in a string in csharp

To get variables that are separated by commas within a string in C#, you can use the Split() method from the String class. This method splits a string into an array of substrings based on a specified delimiter.

Here's an example:

main.cs
string inputString = "John,Doe,30,1200.50";

string[] variables = inputString.Split(',');

string firstName = variables[0];   // John
string lastName = variables[1];    // Doe
int age = int.Parse(variables[2]); // 30
double salary = double.Parse(variables[3]); // 1200.50
272 chars
9 lines

In this example, we have a string inputString that contains four variables separated by commas. We then use the Split() method to split the string into an array of substrings based on the comma delimiter.

We then access each variable in the array of substrings using the array index. For example, variables[0] gives us the first variable in the string, which is "John". We then parse the third variable, which is an integer, using the int.Parse() method, and the fourth variable, which is a double, using the double.Parse() method.

Note that this example assumes that the variables in the string are in a specific order and of a specific data type. If your input string is more complex or the variables are in a different order, you will need to adjust the code accordingly.

gistlibby LogSnag