java中如何截取字符串中的指定一部分

比如 F:\workspace\ssh_photo\WebContent\uploadFile\1444783552338pic.jpg 想截取后面的文件名。

java用substring函数截取string中一段字符串

在String中有两个substring()函数,如下:

一:String.substring(int start)

参数:

start:要截取位置的索引

返回:

从start开始到结束的字符串

例如:String str = "hello word!";         System.out.println(str.substring(1));

System.out.println(str.substring(3));

System.out.println(str.substring(6));

将得到结果为:

ello word!

lo word!

ord!

如果start大于字符串的长度将会抛出越界异常;

二:String.substring(int beginIndex, int endIndex)

参数:

beginIndex 开始位置索引

endIndex    结束位置索引

返回:

从beginIndex位置到endIndex位置内的字符串

例如:String str = "hello word!";

System.out.println(str.substring(1,4));

System.out.println(str.substring(3,5));

System.out.println(str.substring(0,4));

将得到结果为:

ell

lo 

hell

如果startIndex和endIndex其中有越界的将会抛出越界异常。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-03-30

具体方法如下:   

String useName=

F:\workspace\ssh_photo\WebContent\uploadFile\1444783552338pic.jpg ;

int begin=useName.indexOf(“.”);

int last=useName.length();

System.out.println(useName.substring(begin,last)); 

  方法介绍:  

public String substring(int beginIndex, int endIndex);

第一个int为开始的索引,对应String数字中的开始位置。第二个是截止的索引位置,对应String中的结束位置.

本回答被网友采纳
第2个回答  2015-10-18
可以使用spilt分割;
String str = "F:\workspace\ssh_photo\WebContent\uploadFile\1444783552338pic.jpg
";
String newstr[] = str.spilt('\\',5);
System.out.println(newstr[5]);
第3个回答  2015-10-18
String name="F:\\workspace\\ssh_phot.....\1444783552338pic.jpg";
int i=name.lastIndexOf("\\");
String naem1=name.substring(i+1);本回答被提问者采纳