Java 删除字符串中第三个和最后一个冒号
要删除字符串中第三个和最后一个冒号,可以使用以下方法:
public String removeColon(String str) {
int count = 0;
int thirdColonIndex = -1;
int lastColonIndex = -1;
// 找到第三个和最后一个冒号的索引位置
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ':') {
count++;
if (count == 3) {
thirdColonIndex = i;
}
lastColonIndex = i;
}
}
// 删除第三个冒号和最后一个冒号
if (thirdColonIndex != -1) {
str = str.substring(0, thirdColonIndex) + str.substring(thirdColonIndex + 1);
}
if (lastColonIndex != -1) {
str = str.substring(0, lastColonIndex) + str.substring(lastColonIndex + 1);
}
return str;
}
这个方法首先使用一个计数器count来记录冒号的数量,同时使用两个变量thirdColonIndex和lastColonIndex来记录第三个和最后一个冒号的索引位置。然后使用substring()方法来删除第三个和最后一个冒号,最后返回删除后的字符串。
原文地址: https://www.cveoy.top/t/topic/pgEY 著作权归作者所有。请勿转载和采集!