Stack Overflow has this question answered in many other languages, but not C. So I thought I'd ask, since I have the same issue.
How does one concatenate two integers in C?
Example:
x = 11;
y = 11;
I would like z as follows:
z = 1111;
Other examples attempt to do this with strings. What is a way to do this without strings?
I'm looking for an efficient way to do this in C because in my particular usage, this is going into a time critical part of code.
Thanks in Advance!
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.
In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.
The concatenation of two or more numbers is the number formed by concatenating their numerals. For example, the concatenation of 1, 234, and 5678 is 12345678. The value of the result depends on the numeric base, which is typically understood from context.
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.
unsigned concatenate(unsigned x, unsigned y) {
unsigned pow = 10;
while(y >= pow)
pow *= 10;
return x * pow + y;
}
Proof of compilation/correctness/speed
I avoid the log10
and pow
functions, because I'm pretty sure they use floating point and are slowish, so this might be faster on your machine. Maybe. Profile.
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