首页 > 后端开发 > C++ > 正文

使用C++移除两个零之间的元素

WBOY
发布: 2023-08-29 09:53:05
转载
1370人浏览过

使用c++移除两个零之间的元素

在本文中,我们将讨论如何从一个只包含0和1字符的给定字符串中删除两个零之间的元素。最终的字符串不应包含任何被0包围的字符'1'。例如-

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.

美间AI
美间AI

美间AI:让设计更简单

美间AI 45
查看详情 美间AI

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
登录后复制

理解代码

  • 使用循环从索引1到(长度-1)遍历字符串。
  • 检查第i个索引的前一个和后一个索引是否等于'0'。
  • 如果等于'1',则从该索引处删除该字符。
  • 使用新变量更新长度变量。
  • 最后,在循环结束后打印更新后的字符串。

结论

在本文中,我们讨论了从包含'0'和'1'字符的字符串中删除两个零之间的元素。我们还看到了一个解决相同问题的C++程序;我们可以使用其他语言如C、Java、Python等编写这个程序。希望您觉得本文有帮助。

以上就是使用C++移除两个零之间的元素的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号