JCC
JCC

Reputation: 115

Using string split in C#

I am attempting to read in from a txt file strings that are very similar to the following:

YXCZ0000292=TRUE

or

THS83777930=FALSE

I need to use string split to collect a serial number and put it into a variable I can use later as well as use the true or false portion of the string to set a check box. The serial numbers will never be the same and the TRUE or FALSE portion can be random. Anyone have a good way to handle this one?

Upvotes: 3

Views: 4781

Answers (5)

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19349

Given any string called line, you should be able to do

var parts = line.Split('=');
var serial = parts[0];
var boolean = bool.Parse(parts[1]);

I'm thinking that should work as needed.

Upvotes: 3

maxk
maxk

Reputation: 642

All of the above should work correctly. Once you need to set some checkbox value, you should have a boolean value parsed. See Boolean.Parse()

string s = "YXCZ0000292=TRUE";
string[] parts = s.Split('=');
string serial = parts[0];
bool value = Boolean.Parse(parts[1].ToLower());

to set checkbox value just use checked

checkbox.checked = value

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124642

string s = "THS83777930=FALSE";
var parts = s.Split( '=' );

// error checking here, i.e., make sure parts.Length == 2
var serial = parts.First();
var booleanValue = parts.Last();

Upvotes: 2

Naor
Naor

Reputation: 24063

Assuming the text file contains only one serial and value:

string text=File.ReadAllText("c:\filePath.txt");
string[] parts=text.split("=");

Now parts[0] is the serial and parts[1] is the boolean.

Upvotes: 1

Christopher Currens
Christopher Currens

Reputation: 30695

var ss = String.Split('=');
Console.WriteLine(ss[0]); //YXCZ0000292
Console.WriteLine(ss[1]); //TRUE

Upvotes: 1

Related Questions