linux c++ 目录最后是则去掉例如opttest去掉后为opttest 使用c++98标准给出实现代码
以下是使用C++98标准实现去除目录最后的斜杠的代码示例:
#include <iostream>
#include <string>
std::string removeTrailingSlash(const std::string& path) {
std::string result = path;
size_t lastCharIndex = result.length() - 1;
if (result[lastCharIndex] == '/') {
result = result.substr(0, lastCharIndex);
}
return result;
}
int main() {
std::string directory = "/opt/test/";
std::string updatedDirectory = removeTrailingSlash(directory);
std::cout << "Updated directory: " << updatedDirectory << std::endl;
return 0;
}
该代码定义了一个名为removeTrailingSlash的函数,接受一个std::string类型的参数path,并返回去除目录最后斜杠后的字符串。在removeTrailingSlash函数中,我们首先将传入的path赋值给result变量。然后,我们检查字符串的最后一个字符是否为斜杠,如果是,则使用substr函数从字符串中删除最后一个字符。最后,返回更新后的result字符串。
在main函数中,我们声明一个directory变量并将其初始化为"/opt/test/"。然后,我们调用removeTrailingSlash函数并将返回的结果存储在updatedDirectory变量中。最后,我们打印出更新后的目录
原文地址: https://www.cveoy.top/t/topic/itZm 著作权归作者所有。请勿转载和采集!