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.
You can use the String concatenation operator + to concatenate integers to a string in a clear and concise manner. Note that the compiler implicitly constructs an intermediate StringBuilder object, append the integers, and then call the toString() method.
If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.
Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.
This means that you can no longer perform any math operations on them. To combine numbers, use the CONCATENATE or CONCAT, TEXT or TEXTJOIN functions, and the ampersand (&) operator. Notes: In Excel 2016, Excel Mobile, and Excel for the web, CONCATENATE has been replaced with the CONCAT function.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With