String类的substring()和lastIndexOf()方法的使用
文章目录
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...

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论