Home > Software engineering >  Split string and take part and put this in different variable
Split string and take part and put this in different variable

Time:11-25

Hello I have a variable myvar: "123,2344,567,3334" I need to extract the value after second comma and put this on another varivle that will be used to write in file: my code:

myvar: "123,2344,567,3334"
var items = myvar.Split( ',');
var val=items[3]
// Add on file

string row = Convert.ToString(val)   ";"   "Amount";
StreamWriter file2 = new StreamWriter(fileName, true);
 file2.WriteLine(row);
 file2.Close();
                           

However I got the error : Can not deserialize from string_val.

Is there anything wronf with my code?

I need to extract the value after second comma and put this on another variable.

CodePudding user response:

This should work:

var myvar = "123,2344,567,3334";
var items = myvar.Split(',');
var val=items[2]; // 0-based indexing so 2 is the 3rd element.


File.AppendAllText("file.txt", contents: val);

After this file.txt will contain 567.

CodePudding user response:

Try this:

var myvar = "123,2344,567,3334";
var items = myvar.Split(',');
var val = items[2];

//Write to the file
string row = Convert.ToString(val)   ";"   "Amount";
StreamWriter file2 = new StreamWriter("yourfilename", true);
file2.WriteLine(row);
file2.Close();
  •  Tags:  
  • c#
  • Related