可以使用String类的indexOf和substring方法来实现,在每一次找到冒号后,将冒号的索引加1,并将剩余字符串传入substring方法进行截取。重复这个过程三次即可找到第三次出现的冒号内容。

以下是一个示例代码:

public class Main {
    public static void main(String[] args) {
        String str = "abc:def:ghi:jkl:mno:pqr:stu";
        String colonContent = findThirdColonContent(str);
        System.out.println(colonContent);
    }

    public static String findThirdColonContent(String str) {
        int count = 0;
        int index = -1;
        do {
            index = str.indexOf(':', index + 1);
            if (index != -1) {
                count++;
            }
        } while (index != -1 && count < 3);

        if (count == 3) {
            int nextIndex = str.indexOf(':', index + 1);
            if (nextIndex != -1) {
                return str.substring(index + 1, nextIndex);
            } else {
                return str.substring(index + 1);
            }
        } else {
            return null;
        }
    }
}

在上述示例中,我们定义了一个findThirdColonContent方法,使用do-while循环和indexOf方法来查找冒号的索引,直到找到第三个冒号或没有更多冒号为止。然后使用substring方法截取第三个冒号后到下一个冒号之前的内容,作为结果返回。

请注意,上述代码假设字符串中至少存在三个冒号,并且第三个冒号后面存在内容。如果字符串不满足这些条件,将返回null

java8 查找字符串里面第三次出现的冒号内容 不适用正则

原文地址: https://www.cveoy.top/t/topic/hWc0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录