scatman
scatman

Reputation: 14555

concatenate characters and convert to int

i am using c# and i need some help in this... i have 2 strings

s1="1234"
s2="5678"

i want to create 2 integers so that they become equal to the 1st 2 characters and convert to int. ie

int i1=12  12 is the 1st 2 characters from s1
int i2=56  56 is the 1st 2 characters from s2

Upvotes: 1

Views: 583

Answers (3)

logicnp
logicnp

Reputation: 5836

int i1 = int.parse(s1.SubString(0,2));
int i2 = int.parse(s2.SubString(0,2));

Upvotes: 0

Adam Cobb
Adam Cobb

Reputation: 904

int i1 = Convert.ToInt32(s1.substring(0,2));

And the same for i2 of course, obviously not great using hard-coded index of 2, but you could specify that in some other way through user input or whatever?

Upvotes: 0

Anton Gogolev
Anton Gogolev

Reputation: 115839

Simple:

int i1 = Convert.ToInt32(s1.Substring(0, 2));
int i2 = Convert.ToInt32(s2.Substring(0, 2));

You'll have to add various checks, though (say, what happens if the length of either string is less than 2? or if they contain something other than digits?)

Upvotes: 1

Related Questions