Convert given Binary Array to String in C++ with Examples - GeeksforGeeks

08 Dec, 2021
Given a binary array arr[] containing N integer elements, the task is to create a string s which contains all N elements at the same indices as they were in array arr[].
Example:
Input: arr[] = {0, 1, 0, 1}Output: string = “0101“
Input: arr[] = { 1, 1, 0, 0, 1, 1}Output: string = “110011”
Different methods to convert a binary array to a string in C++ are:
Using to_string() function.Using string stream.Adding char ‘0’ to each integer.Using type casting.Using push_back function.Using transform() function.
Using to_string() function.
Using string stream.
Adding char ‘0’ to each integer.
Using type casting.
Using push_back function.
Using transform() function.
Let’s start discussing each of these functions in detail.
Using to_string() function
The to_string() function accepts a single integer and converts the integer value into a string.
Syntax:
string to_string (int val);
Parameters:val – Numerical value.
Return Value:A string object containing the representation of val as a sequence of characters.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement// the above approach#include <iostream>#include <string>using namespace std;  // Driver codeint main(){  int arr[5] = {1, 0, 1, 0, 1};  int size = sizeof(arr) / sizeof(arr[0]);      // Creating an empty string  string s = "";  for(int i = 0; i < size; i++)   {    s += to_string(arr[i]);  }      cout << s;  return 0;}
Output:
10101
Using string stream
stringstream class is extremely useful in parsing input. A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream class the sstream header file needs to be included in the code.
Basic methods  are:
clear(): to clear the stream
str(): to get and set string object whose content is present in stream.
operator << add a string to the stringstream object.
operator >> read something from the stringstream object,
The stringstream class can be used to convert the integer value into a string value in the following manner:
Insert data into the stream using ‘<<‘ operator.Extract data from stream using ‘>>’ operator or by using str() function.Concatenate the extracted data with the string ‘s’.
Insert data into the stream using ‘<<‘ operator.
Extract data from stream using ‘>>’ operator or by using str() function.
Concatenate the extracted data with the string ‘s’.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement// the above approach#include <iostream>#include <sstream>#include <string>using namespace std;  // Driver codeint main(){  int arr[5] = {1, 0, 1, 0, 1};  int size = sizeof(arr) / sizeof(arr[0]);      // Creating an empty string  string s = "";  for(int i = 0; i < size; i++)   {    // Creating an empty stringstream    stringstream temp;          // Inserting data into the stream    temp << arr[i];          // Extracting data from stream using     // .str() function    s += temp.str();  }      // Printing the string   cout << s;}
Output:
10101
Adding char ‘0’ to each Integer
The approach for adding char ‘0’ to each integer is quite simple.
First step is to declare an empty string s.Iterate over each element of array and concatenate each integer by adding ASCII Value of char ‘0’ with the string s.
First step is to declare an empty string s.
Iterate over each element of array and concatenate each integer by adding ASCII Value of char ‘0’ with the string s.
Logic:The result of adding ASCII value of char ‘0’ with integer 0 and 1 is computed by compiler as follows:
Decimal value of char ‘0’ is 48.
string += 0 + ‘0’      // += 0 + 48       // += 48Char value of decimal 48 is ‘0’.
string += 1 + ‘0’      // += 1 + 48      // += 49Char value of decimal 49 is ‘1’.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement // the above approach#include <iostream>#include <string>using namespace std;  // Driver codeint main() {  int arr[5] = {1, 1, 1, 0, 1};  int size = sizeof(arr) / sizeof(arr[0]);  string s = "";      // Creating an empty string  for(int i = 0; i < size; i++)   {    // arr[i] + 48    // adding ASCII of value of 0     // i.e., 48    s += arr[i] + '0';   }      // Printing the string   cout << s;}
Output:
11101
Using type casting
Before type casting and concatenating there is a need to add 48 to the integer otherwise it will lead to some weird symbols at the output. This happens because in the ASCII table numbers from 0 to 9 have a char value that starts from 48 to 57. In the case of a binary array, the integer will either be 0 or 1.
If it is 0, after adding it will be 48 then after type casting char ‘0’ is concatenated with string.If it is 1, after adding it will be 49 then after type casting char ‘1’ is concatenated with string.
If it is 0, after adding it will be 48 then after type casting char ‘0’ is concatenated with string.
If it is 1, after adding it will be 49 then after type casting char ‘1’ is concatenated with string.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement// the above approach#include <iostream>#include <string>using namespace std;  // Driver codeint main(){  int arr[5] = {1, 1, 1, 0, 1};  int size = sizeof(arr) / sizeof(arr[0]);      // Creating an empty string  string s = "";  for(int i = 0; i < size; i++)   {    arr[i] += 48;    s += (char) arr[i];  }      // Printing the string  cout << s;}
Output:
11101
Using push_back() function
The push_back() member function is provided to append characters. Appends character c to the end of the string, increasing its length by one.
Syntax:
void string:: push_back (char c)
Parameters:  Character which to be appended.  
Return value: None
Error: throws length_error if the resulting size exceeds the maximum number of characters(max_size).
Note:Logic behind adding char ‘0’ has been discussed in Method “Adding ‘0’ to integer”.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement // the above approach#include <iostream>#include <vector>using namespace std;  // Driver codeint main() {  int arr[5] = {1, 0, 1, 0, 1};  int size = sizeof(arr) / sizeof(arr[0]);  vector<char> s;  for(int i = 0; i < size; i++)   {    s.push_back(arr[i] + '0');  }  for(auto it : s)   {    cout << it;  }}
Output:
10101
Using transform() function
The transform() function sequentially applies an operation to the elements of an array and store the result in another output array. To use the transform() function include the algorithm header file. 
Below is the C++ program to implement the above method:
C++
// C++ program to implement// the above method#include <iostream>#include <algorithm>using namespace std;  // define int to char functionchar intToChar(int i) {  // logic behind adding 48 to integer   // is discussed in Method "using type  // casting".  return i + 48;}  // Driver codeint main() {  int arr[5] = {1, 0, 1, 0, 1};  int size = sizeof(arr) / sizeof(arr[0]);  char str[size + 1];   transform(arr, arr + 5, str, intToChar);      // Printing the string  cout << str;}
Output:
10101
Arrays
strings
C++
Strings
Arrays
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack