Combine 2 integer's text not add them together
Asked Answered
P

3

7

I have two integers, x and y. What I am trying to do, is combine the numbers in both, not add them together. I have tried to do this:

int x = 5;
int y = 10;
sum = x + y;

But that makes the output 15. What I am wondering is if there is any way to combine them, so that the output would be 510.

5 + 10 = 510

That is what I am trying to accomplice.

I know I could do something like this:

int x = 5;
int y = 10;
int sum;
sum = Convert.ToInt32(x.ToString() + y.ToString());

But that seems like a sloppy way to do it. Is there a better way to do this?

Thanks.

Perturb answered 25/1, 2014 at 22:26 Comment(7)
You need to concatenate strings, so concatenate strings.Caskey
AFAIK that's the shortest way to achieve it. You could use some maths to do it, but it will be longer.Krissie
@SergeyBerezovskiy How do you do that?Perturb
@Perturb stringA + stringBCaskey
@SergeyBerezovskiy I'm using a int though...Perturb
@Perturb you're already doing it, you called it sloppyAdrianople
@Perturb where that int comes from? And why you need to concatenate these values as strings?Caskey
T
16

A little simplier:

int x = 5;
int y = 10;
int sum;
sum = Convert.ToInt32("" + x + y);

Notice that you need convertion in any case. Implicit conversion is used here.

Theosophy answered 25/1, 2014 at 22:33 Comment(3)
Brilliant! Just what I wanted! I would upvote, but my daily limit is reached. I'll upvote tomorrow!Perturb
Thanks for the article to CodeProject! Great article!Perturb
If it would be a method with params int[] and a linq statement I would up vote it. :)Selflove
K
5
int x = 5;
int y = 11;

var z = (int)(x * Math.Pow(10, (int)Math.Log10(y) + 1) + y);
Karleenkarlen answered 25/1, 2014 at 22:30 Comment(3)
I like the math but is this really more simple?Columbium
@Columbium I didn't say that. Just without string ops.Karleenkarlen
As I said, you can use maths, but not only the answer is longer but the intent is clearly lost...Krissie
L
1

Another approach is with strings since you are treating these as strings already:

int x = 5;
int y = 10;
string value = string.Format("{0}{1}", x, y);
sum = int.Parse(value);

That makes the output 510, and it is a little cleaner than your "sloppy way to do it".

Lebron answered 6/2, 2023 at 21:53 Comment(3)
Even shorter var value = $"{x}{y}";Presentationism
@Neil, I started to put that, but being a 10 year old question, I put the output in 10 year old C#. :)Lebron
A 10 year old question that just appeared at the top of the C# questions. Is SO having a senior moment :-)Presentationism

© 2022 - 2024 — McMap. All rights reserved.