Convert given Binary Array to String in C++ with Examples
Last Updated :
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.
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 code
int 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'.
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 code
int 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.
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
// += 48
Char value of decimal 48 is '0'.
string += 1 + '0'
// += 1 + 48
// += 49
Char 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 code
int 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.
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 code
int 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 code
int 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 function
char intToChar(int i)
{
// logic behind adding 48 to integer
// is discussed in Method "using type
// casting".
return i + 48;
}
// Driver code
int 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
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read