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
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;
}
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";
}
ab
ab