java字符串变量,其值为
String path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"
我想删除最后四个字符,即.null
。我可以使用哪种方法来拆分。
发布于 2013-10-09 06:20:11
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"
发布于 2012-02-03 15:42:10
path = path.substring(0, path.length() - 5);
发布于 2013-09-09 00:24:28
令我惊讶的是,所有其他答案(截至2013年9月8日)要么涉及计算子字符串".null"
中的字符数,要么在没有找到子串的情况下抛出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);
}
}
如果没有找到子字符串,则不会发生任何操作,因为没有要截断的内容。你不会得到StringIndexOutOfBoundsException
的。此外,您不必自己计算子字符串中的字符。
https://stackoverflow.com/questions/9125241
复制相似问题