Java 删除字符串中第三个和最后一个冒号
要删除字符串中的第三个和最后一个冒号,可以使用以下 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
代码解析:
- 首先定义一个计数器
count来记录冒号出现的次数。 - 使用
StringBuilder类来构建新的字符串,并定义一个变量lastIndex记录上一次添加字符的位置。 - 遍历字符串,如果当前字符为冒号,则计数器加 1。
- 当计数器等于 3 时,跳过当前字符,即删除第三个冒号。
- 当计数器大于 3 时,删除上一次添加字符,即删除最后一个冒号。
- 遍历结束后,将
StringBuilder对象转换为字符串并输出。
其他方法:
除了使用循环遍历的方法,还可以使用正则表达式来删除字符串中特定的字符。例如,可以使用以下代码来删除第三个和最后一个冒号:
String result = str.replaceAll('(:(.*?:){2}):', '$1');
注意:
- 以上代码仅供参考,实际应用中可能需要根据具体需求进行修改。
- 在使用正则表达式时,需要确保正则表达式与目标字符串匹配。
- 对于复杂的字符串操作,建议使用专业的字符串处理库,例如 Apache Commons Lang 等。
原文地址: https://www.cveoy.top/t/topic/pgEX 著作权归作者所有。请勿转载和采集!