获取路径删除和串联字符

GetPath Remove and Concatenation Char

本文关键字:字符 路径 删除 获取      更新时间:2023-10-16

我将获得环境"APPDATA"并返回到从APPDATA\Roaming到APPDATA的上一个目录,然后我想与另一个目录APPDATA\Local\合并,最后将"\"替换为"\"。目前我遇到了问题。如何返回目录?

代码假设是

#include <string>
#include <iostream>
#include <algorithm> 
char* path;
path= getenv("APPDATA"); <!--GetEnv APPDATA-->
??? <!-- Go back directory -->
strncpy(path,"Local\stuff,12); <!-- add front directory-->
<!-- Replace slash to double slash -->
std::string s = path;
std::replace(s.begin(),s.end(), '','');

您是否正在尝试删除字符串中的最后一个目录?

如果是这样,您可以使用 std::string::find_last_of( "\\" ) 查找最后一个斜杠,然后使用返回值创建子字符串。 以下示例将执行此操作。

std::string path = getenv("APPDATA"); //<!--GetEnv APPDATA-->
//??? <!-- Go back directory -->
std::size_t slashPosition = path.find_last_of( "\" );
// Remove slash at the end if found easier to handle if trailing slash is/not found)
path = path.substr( 0, slashPosition ); 
path += "\Local\stuff"; //<!-- add front directory-->

我删除了用双背替换单背的代码,因为它无法按编写的方式工作,我认为没有必要。 我还对路径变量使用了 std::string 来利用 std::string 中的方法。