模拟Excel中SUBSTITUTE函数

Excel中的SUBSTITUTE是一个很有用的字符串替换函数,其说明如下:

说明

在文本字符串中用 new_text 替换 old_text。 如果需要在某一文本字符串中替换指定的文本,请使用函数 SUBSTITUTE;如果需要在某一文本字符串中替换特定位置处的任意文本,请使用函数 REPLACE。

语法

SUBSTITUTE(text, old_text, new_text, [instance_num])

SUBSTITUTE 函数语法具有下列参数:

文本 必需。 需要替换其中字符的文本,或对含有文本(需要替换其中字符)的单元格的引用。

old_text 必需。 需要替换的文本。

new_text 必需。 用于替换 old_text 的文本。

Instance_num 可选。 指定要用 new_text 替换 old_text 的事件。 如果指定了 instance_num,则只有满足要求的 old_text 被替换。 否则,文本中出现的所有 old_text 都会更改为 new_text。

Java实现:

public static String substitute(String src, String oldText, String newText,
int... instancePositions) {
/*
* 由于直接使用split方法会涉及正则表达式, 但无法确认oldText中是否含有正则表达式的元字符,
* 如:[]^$|等,因此先获取动态的分割符, 将oldText用replace方法(此方法不涉及正则表达式)替换为获取到的分隔符
*/
String splitStr = getSplitStr(src);
// System.out.println(splitStr);
String dealSrc = src.replace(oldText, splitStr);
// 使用获取到的分隔符分割
String[] splitArr = dealSrc.split(splitStr);
int arrLen = splitArr.length;
StringBuffer sbf = new StringBuffer();
for (int i = 0; i < arrLen; i++) {
boolean needReplace = needReplace(i, instancePositions);
if (needReplace && i != 0) {
sbf.append(newText);
} else {
sbf.append(oldText);
}
sbf.append(splitArr[i]);
}
return sbf.toString().substring(oldText.length());
}

private static String getSplitStr(String src) {
StringBuilder sbd = new StringBuilder();
boolean contains = false;
do {
sbd.append("@");
contains = src.contains(sbd);
} while (contains);
return sbd.toString();
}

private static boolean needReplace(int num, int[] nums) {
boolean needReplace = false;
// 当未输入需要替换的位置时,默认全部替换,因此直接返回true
if (nums.length == 0) {
return true;
}
for (int i = 0; i < nums.length; i++) {
if (num == nums[i]) {
needReplace = true;
break;
}
}
return needReplace;
}

public static void main(String[] args) {
String s = substitute("yan@@tian@i@love@u", "@@", " ");
System.out.println(s);
}
原文地址:https://www.cnblogs.com/yw0219/p/10629615.html