index第二个子字符串出现的位置

str1.indexOf("_", str1.indexOf("_") + 1)

例子问题:
知道规则,截取不定长字段。假设字符串"WWW_01_01_02.txt" 和 "WWW_MY01_01_02.txt"的01和MY01代表的是存放的文件夹名称,这时候我们要获取文件夹名称。
上代码

package file;

public class FindStr {
    public static void main(String[] args) {
        String str1 ="WWW_01_01_02.txt";
        String str2 ="WWW_MY01_01_02.txt";
        System.out.println("第二个子字符串出现的下标:"+str1.indexOf("_", str1.indexOf("_") + 1) );
        System.out.println("查找第一个文件存放文件夹为:"+str1.substring(4,str1.indexOf("_", str1.indexOf("_") + 1)));
        System.out.println("查找第二个文件存放文件夹为:"+str2.substring(4,str2.indexOf("_", str2.indexOf("_") + 1)));
    }
}

输出
在这里插入图片描述

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐