'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
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 1:[1]
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
Solution 2:[2]
string removeNumbers(string str)
{
    int current = 0;
    for (int i = 0; i < str.length(); i++)
    {
        if (!isdigit(str[i])) {
            str[current] = str[i];
            current++;
        }
    }
    return str.substr(0, current);
}
int main()
{
     string str;
     cout <<"Enter the string : " <<endl;
     getline(cin,str);
     cout <<"Modified string : " <<removeNumbers(str) <<endl;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | |
| Solution 2 | Basicthings | 
