How to remove string trailing path separator in C++

2 Answers

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

void removeTrailingSeparator(std::string& path) {
    if (!path.empty() && (path.back() == '/' || path.back() == '\\')) {
        path.pop_back();
    }
}

int main() {
    std::string path = "c:/example/path/";
    
    removeTrailingSeparator(path);
    
    std::cout << "Modified path: " << path << std::endl;
}



/*
run:

Modified path: c:/example/path

*/

 



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

void removeTrailingSeparator(std::string& path) {
    if (!path.empty() && (path.back() == '/' || path.back() == '\\')) {
        path.erase(path.size() - 1);
    }
}

int main() {
    std::string path = "c:/example/path/";
    
    removeTrailingSeparator(path);
    
    std::cout << "Modified path: " << path << std::endl;
}



/*
run:

Modified path: c:/example/path

*/

 



answered Jun 16, 2025 by avibootz
edited Jun 16, 2025 by avibootz

Related questions

2 answers 151 views
1 answer 106 views
1 answer 97 views
2 answers 132 views
2 answers 159 views
1 answer 92 views
1 answer 118 views
...