'Joining two characters in c++
My requirement is to join two characters. For example
int main()
{
char c1 ='0';
char c2 ='4';
char c3 = c1+c2;
cout<< c3;
}
The value which I am expecting is 04. But what I am getting is d
.
I know that char is single byte. My requirement is that in the single Byte of C3 is possible to merge/join/concat the c1,c2 and store the value as 04
Solution 1:[1]
A char
is not a string
. So you can first convert the first char to a string and than add the next ones like:
int main()
{
char c1 ='0';
char c2 ='4';
auto c3 = std::string(1,c1)+c2;
std::cout<< c3;
}
What is "magic" std::string(1,c1)
:
It uses the std::string constructor of the form: std::string::string (size_t n, char c);
. So it "fills" the string with one single character of your given c1 which is the 0
.
If you add chars you get the result of adding the numeric value of it which is:
int main() {
std::cout << (int)c1 << std::endl;
std::cout << (int)c2 << std::endl;
std::cout << (int)c1+c2 << std::endl;
std::cout << char(c1+c2) << std::endl;
}
The numeric value as int from 0
is 48, from 4
it is 52. Add both you get 100. And 100 is a d
in ascii coding.
Solution 2:[2]
What you want is called a string of characters. There are many ways to create that in C++. One way you can do it is by using the std::string
class from the Standard Library:
char c1 = '0';
char c2 = '4';
std::string s; // an empty string
s += c1; // append the first character
s += c2; // append the second character
cout << s; // print all the characters out
Solution 3:[3]
A char
is no more than an integral type that's used by your C++ runtime to display things that humans can read.
So c1 + c2
is a instruction to add two numbers, and is an int
type due to the rules of type conversions. If that's too big to fit into a char
, then the assignment to c3
would have implementation-defined results.
If you want concatenation, then
std::cout << ""s + c1 + c2;
is becoming, from C++11's user defined literals, the idiomatic way of doing this. Note the suffixed s
.
Solution 4:[4]
Each char in C (and C++) has the length of one byte. What you are doing is adding the actual byte values:
'0' = 0x30
'4' = 0x34
-> '0' + '4' = 0x30 + 0x34 = 0x64 = 'd'
If you want to concatenate those two you will need an array:
int main()
{
char c1 ='0';
char c2 ='4';
char c3[3] = {c1,c2,0}; // 0 at the end to terminate the string
cout<< c3;
return 0;
}
Note that doing those things with chars is C but not C++. In C++ you would use a string, just as Klaus did in his answer.
Solution 5:[5]
What you named "joining" is actually arithmetics on char
types, which implicitly promotes them to int
. The equivalent integer value for a character is defined by the ASCII table ('0' is 48, '4' is 52, hence 48 + 52 = 100, which finally is 'd'). You want to use std::string
when concatenating textual variables via the +
operator.
Solution 6:[6]
You can do somthing like that:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
char a = '0';
char b = '4';
vector<char> c;
c.push_back(a);
c.push_back(b);
cout << c.data() << endl;
return 0;
}
Solution 7:[7]
Simple addition is not suitable to "combine" two characters, you won't ever be able to determine from 22 if it has been composed of 10 and 12, 11 and 11, 7 and 15 or any other combination; additionally, if order is relevant, you won't ever know if it has been 10 and 12 or 12 and 10...
Now you can combine your values in an array or std::string
(if representing arbitrary 8-bit-data, you might even prefer std::array
or std::vector
). Another variant is doing some nice math:
combined = x * SomeFactorLargerThanAnyPossibleChar + y;
Now you can get your two values back via division and modulo calculation.
Assuming you want to encode ASCII only, 128 is sufficient; considering maximum values, you get: 127*128+127 == 127*129 == 2^14 - 1
. You might see the problem with yourself, though: Results might need up to 14 bit, so your results won't fit into a simple char any more (at least on typical modern hardware, where char normally has eight bits only – there are systems around, though, with char having 16 bits...).
So you need a bigger data type for:
uint16_t combined = x * 128U + y;
//^^
Side note: if you use 256 instead, each of x and y will be placed into separate bytes of the two of uint16_t. On the other hand, if you use uint64_t and 127 as factor, you can combine up to 9 ASCII characters in one single data type. In any case, you should always use powers of two so your multiplications and divisions can be implemented as bitshifts and the modulo calculations as simple AND-operation with some appropriate mask.
Care has to be taken if you use non-ASCII characters as well: char might be signed, so to prevent unwanted effects resulting from sign extension when values being promoted to int, you need to yet apply a cast:
uint16_t combined = static_cast<uint8_t>(x) * 128U + static_cast<uint8_t>(y);
Solution 8:[8]
Since a basic char
doesn't have operator+
to concatenate itself with another char
,
What you need is a representation of a string literal using std::string
as suggested by others
or in c++17, you can use string_view
,
char array[2] = {'0', '4'};
std::string_view array_v(array, std::size(array));
std::cout << array_v; // prints 04
Solution 9:[9]
Basics first
In C++ and C, a string ends with '\0'
which is called null
character.
Presence of this null
character at the end differentiates between a string
and char
array. Otherwise, both are contigous memory location.
While calculating string.length()
not counting the null
character at the end is taken care.
Joining/Concatenating two characters
If you join two character using +
operator, then handling the null
character in both strings end will be taken care.
But if you join two char
with +
operator and wish to see it as an string
, it will not happen, because it has no null
character at the end.
See the example below:
char c1 = 'a';
char c2 = 'b';
string str1 = c1 + c2;
cout << str1; // print some garbled character, as it's not valid string.
string str2; // null initialization
str2 = str2 + c1 + c2;
cout << str2; // prints ab correctly.
string s1 = "Hello";
string s2 = "World";
string str3 = s1 + s2;
cout << str3; //prints Hello World correctly.
string str4 = s1 + c1;
cout << str4; //prints Hello a correctly.
Solution 10:[10]
https://github.com/bite-rrjo/STG-char-v2/blob/main/stg.h without external libraries it would be like this
#include "iostream"
#include "lib-cc/stg.h"
using namespace std;
int main(){
// sum two char
char* c1 = "0";
char* c2 = "4";
stg _stg;
_stg = c1;
_stg += c2;
cout << _stg() << endl;
// print '04'
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Donald Duck |
Solution 3 | |
Solution 4 | izlin |
Solution 5 | lubgr |
Solution 6 | CoralK |
Solution 7 | |
Solution 8 | |
Solution 9 | Om Sao |
Solution 10 |