移除 C++ 中字符串中的尾随零


在此程序中,我们将看到如何在 C++ 中移除字符串中的尾随零。有时,某些字符串可能包含尾随零,例如“00023054”。执行此程序后,它将仅返回“23054”。初始零已被移除。

Input: A string with trailing zeros “000023500124”
Output: “23500124”

算法

Step 1: Get the string
Step 2: Count number of trailing zeros n
Step 3: Remove n characters from the beginning
Step 4: return remaining string.

示例代码

 在线演示

#include<iostream>
using namespace std;
main() {
   string my_str = "000023500124";
   int num = 0;
   cout << "Number with Trailing Zeros :" << my_str << endl;
   //count number of trailing zeros in the string
   while(my_str[num] == '0') {
      num++;
   }
   my_str.erase(0, num); //erase characters from 0 to i index
   cout << "Number without Trailing Zeros :" << my_str;
}

输出

Number with Trailing Zeros :000023500124
Number without Trailing Zeros :23500124

更新于:2019 年 7 月 30 日

3K+ 浏览量

启动你的 职业

完成课程即可获得认证

开始
广告
© . All rights reserved.