TRONG chương trình này, chúng ta sẽ xem cách xóa các số không ở cuối chuỗi trong C ++. Đôi khi một số chuỗi có thể chứa các số không ở cuối như "00023054". Sau khi thực hiện chương trình này, nó sẽ chỉ trả về "23054". Các số 0 ban đầu bị xóa.
Input: A string with trailing zeros “000023500124” Output: “23500124”
Thuật toán
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.
Mã mẫu
#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;
} Đầu ra
Number with Trailing Zeros :000023500124 Number without Trailing Zeros :23500124