Java には、文字列の一部/シーケンスを特定の新しいパターンに置き換える replace() および replaceAll() メソッドがあります。その機能の内部はどのように機能しますか? RegEx を使用せずに、文字列 OldPattern、NewPattern を入力し、OldPattern のすべての発生を NewPattern に再帰的に置き換える関数を作成する必要があるとしたらどうでしょうか。文字列入力の反復を使用して次のコードを実行しましたが、うまくいくようです。入力が文字列ではなく characterArray の場合はどうなるでしょうか?
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();
}