移除 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP