views:

688

answers:

14

hi,

I have the following values:

int a=1; 
int b=0;
int c=2;
int d=2;
int e=1;

How do i concatenate these values so that i end up with a String that is 10221; please note that multiplying a by 10000, b by 1000.....and e by 1 will not working since b=0 and therefore i will lose it when i add the values up.

Thnks you in advance.

+6  A: 

Actually,

int result = a * 10000 + b * 1000 + c * 100 + d * 10 + e;
String s = Integer.toString(result);

will work.

Note: this will only work when a is greater than 0 and all of b, c, d and e are in [0, 9]. For example, if b is 15, Michael's method will get you the result you probably want.

Toon Van Acker
Consider the case when a is 0...
Jon Skeet
thanks, but what if a=0? Then I would lose a wouldn't I?
Shamli
Consider that considered, added it to the note.
Toon Van Acker
+3  A: 

If you multiply b by 1000, you will not loose any of the values. See below for the math.

10000
    0
  200
   20
    1
=====
10221
Daniel A. White
what if my first value is equal to 0?
Shamli
It would still work. It will give you the proper value. Do you need it to be exactly 5 chars long?
Daniel A. White
+4  A: 
StringBuffer sb = new StringBuffer();
sb.append(a).append(b).append(c)...

Keeping the values as an int is preferred thou, as the other answers show you.

Björn
`StringBuilder` in this case is an overkill; plain old `+` is fine and much more readable.
polygenelubricants
Readable for who? I prefer the StringBuffer/StringBuilder in this case, and agreeing with Jon Skeets comment to Michaels answer.
Björn
+1  A: 

I would suggest converting them to Strings.

StringBuilder concatenated = new StringBuilder();
concatenated.append(a);
concatenated.append(b);
/// etc...
concatenated.append(e);

Then converting back to an Integer:

Integer.valueOf(concatenated.toString());
Grundlefleck
He seems to want a String as the end result, so the parsing is unnecessary (and if that were actually wanted, the correct solution would be to just add up the numbers without any String tomfoolery)
Michael Borgwardt
Good point on him wanting a String, but if the numbers were just added, the result would be 6, not 10221...
Grundlefleck
@polygenelubricants: Totally agree with you - forget this answer, Michael or Jon's answer are the best solutions going on the information given :)
Grundlefleck
@polygenelubricants: ... or yours ;-)
Grundlefleck
A: 

Use StringBuilder

StringBuilder sb = new StringBuilder(String.valueOf(a));
sb.append(String.valueOf(b));
sb.append(String.valueOf(c));
sb.append(String.valueOf(d));
sb.append(String.valueOf(e));
System.out.print(sb.toString());
Shervin
+2  A: 

Others have pointed out that multiplying b by 1000 shouldn't cause a problem - but if a were zero, you'd end up losing it. (You'd get a 4 digit string instead of 5.)

Here's an alternative (general purpose) approach - which assumes that all the values are in the range 0-9. (You should quite possibly put in some code to throw an exception if that turns out not to be true, but I've left it out here for simplicity.)

public static String concatenateDigits(int... digits)
{
    char[] chars = new char[digits.length];
    for (int i = 0; i < digits.length; i++)
    {
        chars[i] = (char)(digits[i] + '0');
    }
    return new String(chars);
}

In this case you'd call it with:

String result = concatenateDigits(a, b, c, d, e);
Jon Skeet
+9  A: 

The easiest (but somewhat dirty) way:

String result = "" + a + b + c + d + e

Edit: I don't recommend this and agree with Jon's comment. Adding those extra empty strings is probably the best compromise between shortness and clarity.

Michael Borgwardt
Dirty? What? http://stackoverflow.com/questions/2506474/is-concatenating-with-an-empty-string-to-do-a-string-conversion-really-that-bad
polygenelubricants
@polygenelubricants: well, I happen to disagree with the majority opinion on that point.
Michael Borgwardt
I'm not a fan of this - I think `a + "" + b + "" + c + "" + d + "" + e ` would be clearer, myself - although more longwinded, of course. It's just too easy to look at "a + b" and think that will be adding the integers together, IMO.
Jon Skeet
@polygenelubricants: Thanks for pointing out that question - I hadn't spotted it before...
Jon Skeet
I think I would use a StringBuffer with chained appends.
extraneon
Isn't direct string concatenation a little inefficient compared to StringBuffer/Builder methods ?
Andrei Ciobanu
@Andrei: What is the root of all evil again? Besides, one-line string concatenation will be compiled into a StringBuilder. It's only in more complex scenarios (usually involving loops) where concatenation should be avoided.
Michael Borgwardt
@Michael, thank you for clarification Michael, didn't know that.
Andrei Ciobanu
What about `"" + (a) + (b) + (c) + (d) + (e)`? Just as concise, and it draws just enough attention to itself that you go "Ah, I see what's going on here...".
polygenelubricants
Yes, the "(", ")" make the code more readable.
Andrei Ciobanu
+13  A: 

Michael Borgwardt's solution is the best for 5 digits, but if you have variable number of digits, you can use something like this:

public static String concatenateDigits(int... digits) {
   StringBuilder sb = new StringBuilder(digits.length);
   for (int digit : digits) {
     sb.append(digit);
   }
   return sb.toString();
}
polygenelubricants
Thanks everyone for your answers, I'm always working with 5 digits, but in many cases they start with 0, so Michael's way's the wat way ;-)
Shamli
This also works with 0s. For 5 digits, it always give the same result as Michael's; its only advantage (which you don't need) is that it works with variable number of digits.
polygenelubricants
+1 For pointing the use of Variable-Length Arguments Lists.
Andrei Ciobanu
Varargs + foreach combo is best.
polygenelubricants
this is cleaner and has better performance too... string concatenation is messy and results in a lot of unnecessary string generation. modern VMs may mitigate that... not sure, but i think this is much cleaner nonetheless.
PaulP1975
+1  A: 

People were fretting over what happens when a == 0. Easy fix for that...have a digit before it. :)

int sum = 100000 + a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.valueOf(sum).substring(1));

Biggest drawback: it creates two strings. If that's a big deal, String.format could help.

int sum = a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.format("%05d", sum));
cHao
A: 

You can Use

String x = a+"" +b +""+ c+""+d+""+ e;
int result = Integer.parseInt(x);
Ali Shulli
The aim is to go *from* integers *to* a string...
Jon Skeet
+2  A: 

For fun... how NOT to do it ;-)

String s = Arrays.asList(a,b,c,d,e).toString().replaceAll("[\\[\\], ]", "");

Not that anyone would really think of doing it this way in this case - but this illustrates why it's important to give access to certain object members, otherwise API users end up parsing the string representation of your object, and then you're stuck not being able to modify it, or risk breaking their code if you do.

JRL
+3  A: 

just to not forget the format method

String s = String.format("%s%s%s%s%s", a, b, c, d, e);

(%1.1s%1.1s%1.1s%1.1s%1.1s if you only want the first digit of each number...)

Carlos Heuberger
this is the best solution so far
fuzzy lollipop
A: 

Best solutions are already discussed. For the heck of it, you could do this as well: Given that you are always dealing with 5 digits,

(new java.util.Formatter().format("%d%d%d%d%d", a,b,c,d,e)).toString()

I am not claiming this is the best way; just adding an alternate way to look at similar situations. :)

ring bearer
A: 

you can use bit shift operation as well here no?

billy_cool