Delphi截取不确定长度的字符串

juno_393 2017-02-10 03:15:06
 if dlgOpenPath.Execute then
begin
edtFilePath.Text:=Copy(ExtractFileDir(dlgOpenPath.FileName),0,Pos('课件文件',ExtractFileDir(dlgOpenPath.FileName))+7);
end;

上面代码是获取文件所处文件夹的根目录的路径;
如一、E://课件文件/XX/XXX.mp4要获取的为E://课件文件;
二、E://课件文件(初中)/XX/XXX.mp4要获取的为E://课件文件(初中);
之前想通过截取字符串来获取,但发现无法获取字符串长度请问要怎么获取。
...全文
567 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
santiaodahan 2017-02-10
  • 打赏
  • 举报
回复
Copy(strPath, 1, 3)+Copy(strPath,4, Pos('\', Copy(strPath, 4, Length(strPath)-3))-1); 也可以这样,它的优势是少引用一个单元。
juno_393 2017-02-10
  • 打赏
  • 举报
回复
谢谢两位大神了。
  • 打赏
  • 举报
回复
引用 6 楼 juno_393 的回复:
[quote=引用 2 楼 DelphiGuy 的回复:] function GetRootPath(const Path: string): string; var Len: integer; begin Len := Pos('/', Path); if Len = 0 then Len := Length(Path) + 1; Result := Copy(Path, 1 Len - 1); end;
这个是获取的文件的完整路径啊。我要获取的是盘符+根目录[/quote] 呃,确实有问题,这样就好了: function GetRootPath(const Path: string): string; var Len: integer; begin Len := PosEx('\', Path, Pos(':\', Path) + 2); if Len = 0 then Len := Length(path) + 1; Result := Copy(Path, 1, Len - 1); end; 注意文件全路径是E:\课件文件(初中)\XX\XXX.mp4这种形式,没有两个\。否则用Pos(':\\', Path)
juno_393 2017-02-10
  • 打赏
  • 举报
回复
引用 2 楼 DelphiGuy 的回复:
function GetRootPath(const Path: string): string; var Len: integer; begin Len := Pos('/', Path); if Len = 0 then Len := Length(Path) + 1; Result := Copy(Path, 1 Len - 1); end;
这个是获取的文件的完整路径啊。我要获取的是盘符+根目录
santiaodahan 2017-02-10
  • 打赏
  • 举报
回复
引用 2 楼 DelphiGuy 的回复:
function GetRootPath(const Path: string): string; var Len: integer; begin Len := Pos('/', Path); if Len = 0 then Len := Length(Path) + 1; Result := Copy(Path, 1 Len - 1); end;
这样只会得到盘符,而不是第一层目录。
santiaodahan 2017-02-10
  • 打赏
  • 举报
回复
引用 3 楼 juno_393 的回复:
[quote=引用 1 楼 santiaodahan 的回复:] 先确认一个矛盾的地方,这影响代码。你用打开文件对话框得到的是正斜杠(//)的路径吗?盘符后面是两个正斜杠吗?
不好意思,写错了。应该是E:\[/quote]
uses StrUtils;
Copy(strPath,0, PosEx('\', strPath, 4)-1);
这应该是最简洁的写法。复杂文本截取可以用正则表达式。
juno_393 2017-02-10
  • 打赏
  • 举报
回复
引用 1 楼 santiaodahan 的回复:
先确认一个矛盾的地方,这影响代码。你用打开文件对话框得到的是正斜杠(//)的路径吗?盘符后面是两个正斜杠吗?
不好意思,写错了。应该是E:\
  • 打赏
  • 举报
回复
function GetRootPath(const Path: string): string; var Len: integer; begin Len := Pos('/', Path); if Len = 0 then Len := Length(Path) + 1; Result := Copy(Path, 1 Len - 1); end;
santiaodahan 2017-02-10
  • 打赏
  • 举报
回复
先确认一个矛盾的地方,这影响代码。你用打开文件对话框得到的是正斜杠(//)的路径吗?盘符后面是两个正斜杠吗?

16,742

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧