-
May 21st, 2017, 04:57 PM
#1
[RESOLVED] Leave only numeric characters in std::string
Hello.
I'm trying to remove all non numeric characters from std::string, but I have no idea how to do it...
I tried to using boost:regex etc. from google search, but it doesn't work.
Do you have any solution?
Greetings, genotypek.
-
May 21st, 2017, 11:23 PM
#2
Re: Leave only numeric characters in std::string
You can scan the string once and use the non-numeric characters to build a new string, like
Code:
#include <string>
#include <cctype>
#include <iostream>
std::string source = "hfiukqeoi347cno3p80380709jklhdw5k";
std::string target = "";
for (char c : source) {
if (!std::isdigit(c)) target += c;
}
std::cout << source << " / " << target << std::endl;
-
May 22nd, 2017, 01:06 AM
#3
Re: Leave only numeric characters in std::string
If you really want to "Leave only numeric characters", then your test for characters should be the opposite of wolle's example. You could also #include <algorithm> and do the removal in-place, e.g.,
Code:
source.erase(std::remove_if(source.begin(), source.end(),
[](char c) { return !std::isdigit(c); }),
source.end());
-
May 22nd, 2017, 01:55 AM
#4
Re: Leave only numeric characters in std::string
Another way of doing this:
Code:
#include <algorithm>
#include <iostream>
#include <iterator>
bool isnonnum(char c) {
return !(c >= '0' && c <= '9');
}
int main()
{
std::string src = "hfiukqeoi347cno3p80380709jklhdw5k";
src.erase(std::remove_if(src.begin(), src.end(), isnonnum), src.end());
std::copy(src.begin(), src.end(), std::ostream_iterator<char>(std::cout, ""));
return 0;
}
Last edited by AvDav; May 22nd, 2017 at 02:28 AM.
-
May 22nd, 2017, 11:04 PM
#5
Re: Leave only numeric characters in std::string
Originally Posted by laserlight
If you really want to "Leave only numeric characters", then your test for characters should be the opposite of wolle's example. You could also #include <algorithm> and do the removal in-place, e.g.,
Code:
source.erase(std::remove_if(source.begin(), source.end(),
[](char c) { return !std::isdigit(c); }),
source.end());
Okay, to keep the digits instead of discarding them it's just to remove the ! (not) sign in the code in my post #2.
First I suspected your solution was inefficient but then I realized it's not. It's even an established idiom,
https://en.wikipedia.org/wiki/Erase%...93remove_idiom
In-place manipulation of strings feels awkward to me but it's probably just my Java background . Of course one can always modify a copy rather than the original string but then on the other hand one is almost back to the iterative approach I suggested so I think I'll stick to it since it's more transparent to me.
Last edited by wolle; May 23rd, 2017 at 12:53 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|