Search code examples
c++stringerase

Getting a word or sub string from main string when char '\' from RHS is found and then erase rest


Suppose i have a string as below

input = " \\PATH\MYFILES This is my sting "

output = MYFILES

from RHS when first char '\' is found get the word (ie MYFILES) and erase the rest.

Below is my approach i tired but its bad because there is a Runtime error as ABORTED TERMINATED WITH A CORE.

Please suggest cleanest and/or shortest way to get only a single word (ie MYFILES ) from the above string?

I have searching and try it from last two days but no luck .please help

Note: The input string in above example is not hardcoded as it ought to be .The string contain changes dynamically but char '\' available for sure.

std::regex const r{R"~(.*[^\\]\\([^\\])+).*)~"} ;
std::string s(R"("  //PATH//MYFILES     This is my sting    "));
std::smatch m;
int main()
{

if(std::regex_match(s,m,r))
{
std::cout<<m[1]<<endl;

}
}
}

Solution

  • To erase the part of a string, you have to find where is that part begins and ends. Finding somethig inside an std::string is very easy because the class have six buit-in methods for this (std::string::find_first_of, std::string::find_last_of, etc.). Here is a small example of how your problem can be solved:

    #include <iostream>
    #include <string>
    
    int main() {
        std::string input { " \\PATH\\MYFILES This is my sting " };
        auto pos = input.find_last_of('\\');    
    
        if(pos != std::string::npos) {
            input.erase(0, pos + 1);
    
            pos = input.find_first_of(' ');
            if(pos != std::string::npos)
                input.erase(pos);
        }
    
        std::cout << input << std::endl;
    }
    

    Note: watch out for escape sequences, a single backslash is written as "\\" inside a string literal.