[英]Removing a substring from a string
I have a very simple question and just can't get my code to work in Java. 我有一个非常简单的问题,只是无法让我的代码在Java中工作。 I want to return a string that indicates a filepath, but extracts a certain portion of that path if it it exists.
我想返回一个指示文件路径的字符串,但是如果存在则提取该路径的特定部分。
So, my input might be "c:/lotus/notes/data/directory/mydatabase.nsf" and I want to return only "directory/mydatabase.nsf". 因此,我的输入可能是“ c:/lotus/notes/data/directory/mydatabase.nsf”,而我只想返回“ directory / mydatabase.nsf”。 Sometimes, the path provided will already leave out the "c:/lotus/notes/data/" because it is being accessed on the server rather than locally.
有时,提供的路径将已经忽略了“ c:/ lotus / notes / data /”,因为它是在服务器而不是本地访问的。
public String getDataPath ( String path ) {
int pathStart;
boolean pathContains;
String lowerPath;
lowerPath = path.toLowerCase();
pathStart = lowerPath.indexOf("c:/lotus/notes/data");
if ( pathStart >= 0) {
// 20 characters in "c:/lotus/notes/data/"
return path.substring(19);
}
pathContains = lowerPath.contains("lotus/notes/data");
if ( pathContains ) {
// 20 characters in "c:/lotus/notes/data/"
return path.substring(19);
}
return path;
}
This is simple, but somehow, I can't get it right. 这很简单,但是以某种方式,我做不到。 Neither of my if's ever evaluates as true.
我的两个if都不认为是真的。
You can simply do a path.replaceAll("c:/lotus/notes/data", "")
. 您可以简单地执行
path.replaceAll("c:/lotus/notes/data", "")
。 This will remove the leading path name if it is contained in the string, else the string will not change. 如果字符串中包含前导路径名,它将删除该字符串,否则该字符串将不会更改。
把事情简单化:
path.replace("c:/lotus/notes/data", "");
Take a look at the Path
interface: 看一下
Path
界面:
It is used to do exactly what you want: Extract informations about the single parts of a path. 它可用于完全满足您的要求:提取有关路径单个部分的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.