一个java String变量,其值为
String path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"
Run Code Online (Sandbox Code Playgroud)
我想删除最后四个字符,即.null
.我可以使用哪种方法进行拆分.
Jon*_*eet 130
我想你要删除最后五个字符('.','n','u','l','l'):
path = path.substring(0, path.length() - 5);
Run Code Online (Sandbox Code Playgroud)
注意您需要如何使用返回值 - 字符串是不可变的,因此substring
(和其他方法)不会更改现有字符串 - 它们返回对具有适当数据的新字符串的引用.
或者更安全一点:
if (path.endsWith(".null")) {
path = path.substring(0, path.length() - 5);
}
Run Code Online (Sandbox Code Playgroud)
但是,我会尝试更高层次地解决这个问题.我的猜测是你只得到了".null",因为其他一些代码正在做这样的事情:
path = name + "." + extension;
Run Code Online (Sandbox Code Playgroud)
哪里extension
是null.相反,我会以此为条件,所以你永远不会得到错误的数据.
(如问题评论中所述,你真的应该浏览一下String
API.它是Java中最常用的类之一,所以没有理由不熟悉它.)
Mat*_*kan 31
import org.apache.commons.lang3.StringUtils;
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"
StringUtils.removeEnd(path, ".null");
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf"
Run Code Online (Sandbox Code Playgroud)
我很惊讶地看到所有其他答案(截至2013年9月8日)要么计算子字符串中的字符数,要么在未找到子字符串时".null"
抛出a StringIndexOutOfBoundsException
.或两者 :(
我建议如下:
public class Main {
public static void main(String[] args) {
String path = "file.txt";
String extension = ".doc";
int position = path.lastIndexOf(extension);
if (position!=-1)
path = path.substring(0, position);
else
System.out.println("Extension: "+extension+" not found");
System.out.println("Result: "+path);
}
}
Run Code Online (Sandbox Code Playgroud)
如果找不到子串,则没有任何事情发生,因为没有什么可以切断的.你不会得到的StringIndexOutOfBoundsException
.此外,您不必在子字符串中自己计算字符数.
归档时间: |
|
查看次数: |
142402 次 |
最近记录: |