How to remove the trailing slashes from a string in C++

2 Answers

0 votes
#include <iostream>
#include <regex>
#include <string>

std::string removeTrailingSlashes(const std::string& str) {
    return std::regex_replace(str, std::regex("/+$"), "");
}

int main() {
    std::cout << removeTrailingSlashes("/ABC/") << std::endl;
    std::cout << removeTrailingSlashes("/ABC////") << std::endl;
    std::cout << removeTrailingSlashes("/ABC") << std::endl;
}


/*
run:

/ABC
/ABC
/ABC

*/

 



answered Jun 13, 2025 by avibootz
0 votes
#include <iostream>
#include <string>

void removeTrailingSlashes(std::string& str) {
    while (!str.empty() && str.back() == '/') {
        str.pop_back();
    }
}

int main() {
    std::string str = "/ABC////";
    
    removeTrailingSlashes(str);
    
    std::cout << str << std::endl;
}



/*
run:

/ABC

*/

 



answered Jun 13, 2025 by avibootz

Related questions

2 answers 136 views
1 answer 117 views
1 answer 133 views
1 answer 125 views
2 answers 226 views
...