Removing Elements Between the Two Zeros using C++


In this article, we will discuss how to remove elements between two zeros from a given string that contains only zero’s and one’s character. The final string should not contain any character ‘1’ surrounded by 0’s. For example −

Input : string = “110010”
Output : “11000”
Explanation: 1 is found between two zeros at the 4th index.

Input : string = “0010”
Output : “000”
Explanation : 1 is found between two zeros at the 2nd index.

Approach to find The Solution

We can apply a simple approach, i.e., traverse the string using a loop and check the previous and next elements whether they are zeros; if yes, then that index is not zero. After that, update the variable with a new length that stores length and print that string.

Example

#include <bits/stdc++.h>
using namespace std;

int main () {
   string str = "110010";
   int length = str.length();
   for (int i = 1; i < length - 1; i++) {
      // checking the element between two zeros
      if ((str.at (i - 1) == '0' && str.at (i + 1) == '0')) {
         // deleting the element
         // if it is found between two 0's
         str.erase (i, 1);

         i--;
         if (i > 0 && str.at (i - 1) == '0')
            i--;

            // updating the length of the string after removing the element.
         length = str.length ();
      }
   }
   cout << "String after removing elements between the two zeros: " << str;
   return 0;
}

Output

String after removing elements between the two zeros: 1100

Understanding the code

  • A loop is used to go through the string from index 1 to (length - 1).
  • Checking the previous and next index of ith index whether it is equal to ‘0’.
  • Removing that character from that index if it is ‘1’.
  • Updating the length variable with a new variable.
  • Finally printing the updated string after the loop ends.

Conclusion

In this article, we discussed removing elements between the two zeros from a string containing ‘0’ and ‘1’ characters. We also see a C++ program to solve the same; we can write this program in any other language like C, java, python, etc. Hope you find this article helpful.

Updated on: 29-Nov-2021

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements