Java 删除字符串中第三个和最后一个冒号的内容
要删除字符串中第三个与最后一个冒号,可以使用以下步骤:
- 使用 'indexOf' 方法找到第三个冒号的索引位置。
- 使用 'lastIndexOf' 方法找到最后一个冒号的索引位置。
- 使用 'substring' 方法将字符串分成三部分:从开始到第三个冒号之前、从第三个冒号之后到最后一个冒号之前、从最后一个冒号之后到结束。
- 将第一部分和第三部分合并在一起。
以下是示例代码:
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' 删除之后得到的新字符串。
原文地址: https://www.cveoy.top/t/topic/pgEV 著作权归作者所有。请勿转载和采集!