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 288 views
1 answer 192 views
1 answer 181 views
2 answers 277 views
2 answers 285 views
1 answer 184 views
1 answer 225 views
...