要删除字符串中的第三个和最后一个冒号,可以使用以下 Java 代码:

public class Main {
    public static void main(String[] args) {
        String str = 'abc:def:ghi:jkl:mno:pqr:stu';
        
        int count = 0;
        int lastIndex = -1;
        StringBuilder sb = new StringBuilder();
        
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ':') {
                count++;
                if (count == 3) {
                    continue;
                }
                
                if (count > 3) {
                    sb.deleteCharAt(lastIndex);
                }
            }
            
            lastIndex = sb.length();
            sb.append(str.charAt(i));
        }
        
        String result = sb.toString();
        System.out.println(result);
    }
}

运行结果为:

abc:def:ghijklmnopqrstu

代码解析:

  1. 首先定义一个计数器 count 来记录冒号出现的次数。
  2. 使用 StringBuilder 类来构建新的字符串,并定义一个变量 lastIndex 记录上一次添加字符的位置。
  3. 遍历字符串,如果当前字符为冒号,则计数器加 1。
  4. 当计数器等于 3 时,跳过当前字符,即删除第三个冒号。
  5. 当计数器大于 3 时,删除上一次添加字符,即删除最后一个冒号。
  6. 遍历结束后,将 StringBuilder 对象转换为字符串并输出。

其他方法:

除了使用循环遍历的方法,还可以使用正则表达式来删除字符串中特定的字符。例如,可以使用以下代码来删除第三个和最后一个冒号:

String result = str.replaceAll('(:(.*?:){2}):', '$1');

注意:

  • 以上代码仅供参考,实际应用中可能需要根据具体需求进行修改。
  • 在使用正则表达式时,需要确保正则表达式与目标字符串匹配。
  • 对于复杂的字符串操作,建议使用专业的字符串处理库,例如 Apache Commons Lang 等。
Java 删除字符串中第三个和最后一个冒号

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

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