Remove empty elements from an array in C++

In this tutorial, we will learn to write the code on how to remove empty elements from an array in C++ programming.


#include <bits/stdc++.h>
using namespace std;
string convertToString(char* a, int size)//function to convert character to string
  int i;
  string s = "";
  for (i = 0; i < size; i++) {
    s = s + a[i];
  return s;
int main()
  char a[] = { 'A',' ','O', ' ', 'K','1','8',' ','e' };//character array

  int size = sizeof(a) / sizeof(char);//determining total elements in array 

  string s = convertToString(a, size);//calling convert function

  cout << s << endl;
    s.erase(remove(s.begin(), s.end(), ' '), s.end());//function to remove empty elements from string
    return 0;


1)In the above code first we created a function to convert the character of the array into the string that has a string as its return type.

2)Inside the function we used a loop that takes every single element from the array and passes it into the declared string “s”.

3)In the main function we declared a character array “a” and then take out its size and stored it in the “size” variable.

4)After that we call the string convert function to convert elements of “a” into string and stored the string in “s”.

5) At the end we used the s.erase() function which is an inbuilt function of the string library used to erase characters from a string and empty spaces.

6)Finally we print our modified string


A O K18 e

In the output first, we are getting the string with empty elements and in the next line, we are getting our modified output without spaces.

Leave a Reply

Your email address will not be published.