【发布时间】:2013-01-22 03:07:45
【问题描述】:
Java 有 replace() 和 replaceAll() 方法可以用给定的新模式替换字符串的部分/序列。该函数的内部是如何工作的?如果我必须编写一个函数来输入字符串、OldPattern、NewPattern 并在不使用 RegEx 的情况下用 NewPattern recursively 替换所有出现的 OldPattern 怎么办? 我已经使用 String 输入的迭代完成了以下代码,它似乎可以工作。如果输入是字符数组而不是字符串怎么办?
public String replaceOld(String aInput, String aOldPattern, String aNewPattern)
{
if ( aOldPattern.equals("") ) {
throw new IllegalArgumentException("Old pattern must have content.");
}
final StringBuffer result = new StringBuffer();
int startIdx = 0;
int idxOld = 0;
while ((idxOld = aInput.indexOf(aOldPattern, startIdx)) >= 0) {
result.append( aInput.substring(startIdx, idxOld) );
result.append( aNewPattern );
//reset the startIdx to just after the current match, to see
//if there are any further matches
startIdx = idxOld + aOldPattern.length();
}
//the final chunk will go to the end of aInput
result.append( aInput.substring(startIdx) );
return result.toString();
}
【问题讨论】:
-
我不确定你在这里问什么。您似乎已经解决了您的问题,将字符数组转换为字符串是微不足道的。
-
如果您的代码工作正常,那么您可以使用
toString()函数将输入的字符数组转换为字符串,执行上述分析,并在返回修改后的字符串时使用将其转换回字符数组toCharAprray()函数。 -
我正在寻找一种使用递归的方法。我仅通过使用循环/迭代方法解决了这个问题。这是一个面试问题,他们要求不使用任何替换/替换所有方法的递归解决方案。
标签: java string recursion replace