Home > Backend Development > C++ > body text

Remove elements between two zeros using C++

WBOY
Release: 2023-08-29 09:53:05
forward
1298 people have browsed it

Remove elements between two zeros using C++

In this article, we will discuss how to remove elements between two zeros from a given string that contains only 0 and 1 characters. The final string should not contain any '1' characters 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.
Copy after login

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) == &#39;0&#39; && str.at (i + 1) == &#39;0&#39;)) {
         // deleting the element
         // if it is found between two 0&#39;s
         str.erase (i, 1);

         i--;
         if (i > 0 && str.at (i - 1) == &#39;0&#39;)
            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;
}
Copy after login

Output

String after removing elements between the two zeros: 1100
Copy after login

Understanding Code

  • Use a loop to traverse the string from index 1 to (length-1).
  • Check whether the previous and next index of the i-th index are equal to '0'.
  • If equal to '1', delete the character from this index.
  • Update the length variable with the new variable.
  • Finally, print the updated string after the loop ends.

Conclusion

In this article, we discussed removing elements between two zeros from a string containing '0' and '1' characters. We also saw a C program that solves the same problem; we can write this program in other languages ​​such as C, Java, Python, etc. Hope you found this article helpful.

The above is the detailed content of Remove elements between two zeros using C++. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template