gpt4 book ai didi

java - 字符串的特定部分

转载 作者:行者123 更新时间:2023-11-30 03:41:55 25 4
gpt4 key购买 nike

如何获取字符串的特定部分,假设我有一个字符串

file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds

我只想得到

C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/

该字符串是动态的,因此它并不总是相同的,我只想从开头和最后部分删除带有 .ds 扩展名的文件单词

我尝试了一下

String resourceURI = configModel.eResource().getURI().toString();
//This line gives: file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds

String sourceFilePath = resourceURI.substring(6, resourceURI.length()-17)
//This line gives C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/

resourceURI.length()-17 可能会产生问题,因为 SWA_Playground.ds 并不总是相同。我怎样才能删除这个字符串的最后一部分

谢谢

最佳答案

您应该使用File class

String sourceFile = "file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds";
Sring filePath = sourceFile.substring(6);

File f = new File(filePath);
System.out.println(f.getParent());
System.out.println(f.getName());

首先删除 file:/ 前缀,然后您就有了一个 Windows 路径,并且可以创建一个 File 实例。

然后使用 getParent() 方法获取文件夹路径,并使用 getName() 获取文件名。

关于java - 字符串的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26648773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com