String类的substring()和lastIndexOf()方法的使用
两个方法
- substring():返回字符串的子字符串;
语法:
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
beginIndex -- 起始索引(包括), 索引从 0 开始;
endIndex -- 结束索引(不包括);
- lastIndexOf():返回指定字符/字符串在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1;
语法:
public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
ch -- 字符;
fromIndex -- 开始搜索的索引位置,索引起始值为0;
str -- 要搜索的子字符串;
举个栗子
场景:上传文件时获取文件的后缀名;描述:前端传来文件时(.txt、.png、.jpg等),我们为了防止重名,一般会在后台对文件进行重命名,但是要保证不改变文件的类型,因此要先拿到文件名后缀,然后再通过拼接操作对文件进行重命名;
//获取文件名
String filename = file.getOriginalFilename();
//文件类型后缀
String suffix = filename.substring(filename.lastIndexOf(".") + 1);
//重命名文件
String nickname = System.currentTimeMillis() + "." + suffix;
参考链接:
https://www.runoob.com/java/j...
https://www.runoob.com/java/j...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。