coze
coze

Reputation: 95

Extract string parts that are separated with commas

I need to extract a string into 3 different variables.

The input from the user will be in this format 13,G,true. I want to store the number in an integer, the "G" in a character and "true" into a string.

But I don't know how to specify the comma location so the characters before or after the comma can be stored in another variable. I'm not allowed to use the LastIndexOf method.

Upvotes: 1

Views: 3012

Answers (5)

James Gardner
James Gardner

Reputation: 506

// original input
string line = "13,G,true";

//  splitting the string based on a character. this gives us
// ["13", "G", "true"]
string[] split = line.Split(',');

// now we parse them based on their type
int a = int.Parse(split[0]);
char b = split[1][0];
string c = split[2];

If what you are parsing is CSV data, I would check out CSV parsing libraries related to your language. For C#, Nuget.org has a few good ones.

Upvotes: 0

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

var tokens = str.Split(",");         //Splits to string[] by comma
var first = int32.Parse(tokens[0]);  //Converts first string to int
var second = tokens[1][0];           //Gets first char of the second string
var third = tokens[2];        

But be aware, that you also need to validate the input

Upvotes: 1

A_Sk
A_Sk

Reputation: 4630

use String.Split

string str='13,G,true';
string[] strArr=str.Split(',');

int32 n=0,intres=0;
char[] charres = new char[1];
string strres="";
if(!Int32.TryParse(strArr[0], out n))
{
intres=n;
}
if(strArr[0].length>0)
{
charres[0]=(strArr[1].toString())[0];
}
strres=strArr[2];


    //you'll get 13 in strArr[0]
    //you'll get Gin strArr[1]
    //you'll get true in strArr[2]

Upvotes: 1

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

string msg = "13,G,true";
var myArray = msg.Split(",");

// parse the elements
int number;
if (!Int32.TryParse(myArray[0], out number) throw new ArgumentException("Whrong input format for number");
string letter = myArray[1];
string b = myArry[2];

// or also with a boolean instead
bool b;
if (!Int32.TryParse(myArray[2], out b) throw new ArgumentException("Whrong input format for boolean");

Upvotes: 5

Paweł Mach
Paweł Mach

Reputation: 745

You are going to need method String.Split('char'). This method splits string using specified char.

    string str = "13,G,true";
    var arrayOfStrings=str.Split(',');

    int number = int.Parse(arrayOfStrings[0]); 

Upvotes: 0

Related Questions