Reputation: 4372
I want to erase none number characters in a string, here is my code for doing it:
int i=0;
while (num[i]!=NULL)
{
if (!(num[i]>='0' && num[i]<='9'))
num.erase(i,1);
i++;
}
think num is e2, then it should be only 2, but it becomes "e". Or if num is 2er4, then it will be 2e4, but it should be 24, how to fix this code?
Upvotes: 2
Views: 8207
Reputation: 4372
Finally I fix it with Joachim Pileborg Tips, Thank You Man;
int i=0;
while (num[i]!=NULL)
{
if (!(num[i]>='0' && num[i]<='9'))
{num.erase(i,1); if ((i-1)>=0) i--;}
else i++;
}
Upvotes: 0
Reputation: 227390
As pointed out by Joachim, the standard library provides you will algorithms that you can trivially use to achieve your objective. The usual approach to remove elements from a standard library container is to use the erase remove idiom. The std::string
class can be considered a container in this case, and the algorithm works as expected. This is a working example, where the std::isdigit
function is used to determine which elements are removed from the string:
#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
int main()
{
std::string s = "abc123def456!!??";
auto it = std::remove_if(s.begin(),
s.end(),
[](char c) { return std::isdigit(c);});
s.erase(it, s.end());
std::cout << s << std::endl;
}
Upvotes: 1
Reputation: 409166
You have a few problems with your code: The first is that your if
condition is to erase characters if they are digits when you state you want the opposite. The other problem is that when you erase a character, then the length of the string is changed so the index i
is no longer valid.
Then you loop while the character as position i
(which may be out of bounds due to the second problem I listed) is not NULL
. But NULL
is only used for pointers, if anything you should check against '\0'
instead. Though I wouldn't recommend that either, as nothing really states that string data inside a std::string
(which I suppose num
is) have to be zero-terminated. Instead loop using the string length, or use iterators.
And like I state in my comment, it can be much more simple than your code, by just calling a single function.
Upvotes: 1