How to concatenate int values in java?
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.
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'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();
}
This worked for me.
int i = 14;
int j = 26;
int k = Integer.valueOf(String.valueOf(i) + String.valueOf(j));
System.out.println(k);
It turned out as 1426
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...)