Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to subtract char out from string in c++?

Hello I want to know how to subract string from string

For example

If string s = "124ab"
I can easily extract integer by using sstream but I don’t know how to extract string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to extract ab from s;
I have tons of string and they don’t have any rule.
s can be "3456fdhgab" or "34a678"

>Solution :

You can use std::isdigit to check if a character is a digit. You can use the erase-remove idiom to remove characters that are digits.

Because std::isdigit has an overload it has to be wrapped in a lambda to be used in the algorithm:

#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>

int main() {
    std::string inp{"124ab"};
    inp.erase(std::remove_if(inp.begin(),inp.end(),[](char c){return std::isdigit(c);}),inp.end());
    std::cout << inp;
}

Output:

ab

And because you asked for using a stringstream, here is how you can extract non-digits with a custom operator<<:

#include <string>
#include <iostream>
#include <cctype>
#include <sstream>

struct only_non_digits {
    std::string& data;    
};

std::ostream& operator<<(std::ostream& os, const only_non_digits& x) {
    for (const auto& c : x.data){
        if (std::isdigit(c)) continue;
        os << c;
    }
    return os;
}    

int main() {
    std::string inp{"124ab"};
    std::cout << only_non_digits{inp} << "\n";
    std::stringstream ss;
    ss << only_non_digits{inp};
    std::cout << ss.str() << "\n";
}

Output:

ab
ab
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading