java替换第N次出现的字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 替换第N次出现的字符串
* @param str 指定字符串
* @param find 需要被替换的字符串
* @param nthOccurrence 要被替换的字符串出现的次数
* @param replace 替换的字符串
* @return 替换后的字符串
*/
public static String replaceNth(String str, String find, int nthOccurrence, String replace) {
int index = str.indexOf(find);
for(int i = 1; i < nthOccurrence; i++) {
index = str.indexOf(find, index + 1);
}

if(index != -1) {
str = str.substring(0, index) + replace + str.substring(index + find.length());
}
return str;
}

例如我要把第二次出现的张三替换为王富贵

image-20230328161748285

若未匹配到指定字符串则不做处理原样返回

image-20230328161826074

查询指定字符串第N次出现的索引

使用 org.apache.commons.lang.StringUtils 下的 ordinalIndexOf方法

1
2
3
int i = StringUtils.ordinalIndexOf("张三,李四,王五,张三,李四,王五,张三,李四,王五", "张三", 2);

System.out.println(i);

image-20230328161949054

若未找到则返回 -1

image-20230328161908326

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 在指定字符串中查询某个字符串出现的第 n 次位置
*
* @param str 指定字符串
* @param target 要查询的字符串
* @param n 第 n 次出现的位置
* @return 如果找到了,返回第 n 次出现的位置;否则返回 -1。
*/
public static int getIndexOf(String str, String target, int n) {
if (str == null || target == null || n <= 0) {
return -1;
}

int index = str.indexOf(target); // 找到第一次出现的位置

// 开始找第 n 次出现的位置
for (int i = 2; i <= n && index != -1; i++) {
index = str.indexOf(target, index + 1);
}

return index;
}
1
2
3
4
5
6
7
// 指定字符串
String str = "Talk Is Cheap, Show Me The Code";
// 需要定位的可以是字符也可以是字符串,本示例是用的字符 'C',需使用 String.valueOf() 方法转为字符串
String target = String.valueOf('C');
// 在 str 中查询 target 出现的第 2 次位置
int index = getIndexOf(str, target, 2);
System.out.println(index);

image-20230328181902986