删除 CString 的开头

Delete the begin of a CString

本文关键字:开头 CString 删除      更新时间:2023-10-16

>我以CString的形式接收文件路径。例如:C:\Program Files\Program\Maps\World\North-America

我需要删除地图之前的所有内容。即 C:\Program Files\Program\,但此文件路径可能不同。

我试过了:

CString noPath = fullPath;
fullPath.Truncate(fullPath.ReverseFind('Maps'));
noPath.Replace(_T(fullPath),_T(""));

这并不一致。它在错误的位置剪切了一些文件路径。该解决方案不需要使用截断/替换,但我不确定如何做到这一点

我熟悉的CString没有Truncate成员,ReverseFind只适用于单个字符,不适用于子字符串; 所以fullPath的类型对我来说是一个谜。

我注意到的一件事:_T(fullPath)出现在您的代码中,但_T宏仅适用于文字(带引号的字符串或字符)。

无论如何,这是一个仅限CString的解决方案。

CString TruncatePath(CString path, CString subdir) {
    CString sub = path;
    const int index = sub.MakeReverse().Find(subdir.MakeReverse());
    return index == -1 ? path : path.Right(index + subdir.GetLength());
}
    ...
CString path     = _T("C:\Program Files\Program\Maps\World\North-America");
CString sub_path = TruncatePath(path, _T("Maps\"));

给你sub_pathMapsWorldNorth-America

您可以使用Delete函数来实现此目的。

例如:

CString path(_T("C:\Program Files\Program\Maps\World\North-America"));
path.Delete(0, path.Find(_T("Maps")));  //pass first index and number of count to delete

现在变量path具有值Maps\World\North-America