我需要一个replace()方法,它可以以不区分大小写的方式替换干草堆字符串中的针字符串。我还需要在没有任何正则表达式的情况下完成此操作。我找不到任何这样的方法,所以我自己写了。这个问题是为了记录它,以防其他人将来发现它有用。如果可以进行任何改进(不使用 String.replace),请随时提出建议。
最佳答案
public static String replace(String needle, String hayStack, String replacement)
{
String origNeedle = needle;
String origHayStack = hayStack;
needle = origNeedle.toLowerCase();
hayStack = origHayStack.toLowerCase();
int hayStackLen = hayStack.length();
int needleLen = needle.length();
int from = 0;
int to;
String stuffBeforeNeedle;
StringBuilder output = new StringBuilder();
do
{
to = hayStack.indexOf(needle, from);
if (to == -1)
to = hayStackLen;
stuffBeforeNeedle = hayStack.substring(from, to);
output.append(stuffBeforeNeedle);
if (to < hayStackLen)
output.append( replacement );
from = hayStack.indexOf(needle, to) + needleLen;
}
while (to < hayStackLen);
return output.toString();
}
关于java - Java中不区分大小写的replace()方法(使用indexOf),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090357/