要删除字符串中第三个与最后一个冒号,可以使用以下步骤:

  1. 使用 'indexOf' 方法找到第三个冒号的索引位置。
  2. 使用 'lastIndexOf' 方法找到最后一个冒号的索引位置。
  3. 使用 'substring' 方法将字符串分成三部分:从开始到第三个冒号之前、从第三个冒号之后到最后一个冒号之前、从最后一个冒号之后到结束。
  4. 将第一部分和第三部分合并在一起。

以下是示例代码:

public class Main {
    public static void main(String[] args) {
        String str = 'a:b:c:d:e:f:g:h:i:j:k';
        int thirdColonIndex = findColonIndex(str, 3);
        int lastColonIndex = str.lastIndexOf(':');
        
        String firstPart = str.substring(0, thirdColonIndex);
        String secondPart = str.substring(thirdColonIndex + 1, lastColonIndex);
        String thirdPart = str.substring(lastColonIndex + 1);
        
        String result = firstPart + secondPart + thirdPart;
        System.out.println(result);
    }
    
    public static int findColonIndex(String str, int occurrence) {
        int colonIndex = -1;
        for (int i = 0; i < occurrence; i++) {
            colonIndex = str.indexOf(':', colonIndex + 1);
            if (colonIndex == -1) {
                break;
            }
        }
        return colonIndex;
    }
}

运行以上代码,输出结果为:

a:bdefghijk

该结果是将第三个冒号 'c' 和最后一个冒号 'k' 删除之后得到的新字符串。

Java 删除字符串中第三个和最后一个冒号的内容

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

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