Решение с Pattern
Вы также можете изменить метод String.replace , использующий интерпретацию символов literal , чтобы заменить только первое вхождение последовательности символов target
:
/**
* Replaces the first subsequence of the <tt>source</tt> character sequence
* that matches the literal target sequence with the specified literal
* replacement sequence.
*
* @param source source sequence on which the replacement is made
* @param target the sequence of char values to be replaced
* @param replacement the replacement sequence of char values
* @return the resulting string
*/
private static String replaceFirst1(CharSequence source, CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
source).replaceFirst(Matcher.quoteReplacement(replacement.toString()));
}
Из документации Pattern.LITERAL :
Если этот флаг указан, то входная строка, которая задает шаблон, обрабатывается как последовательность буквенных символов. Метасимволы или escape-последовательности во входной последовательности не будут иметь специального значения.
Раствор без Pattern
Другой, более эффективный способ, конечно, заключается в использовании подсказки Алекса Мартелли для получения следующей функциональности:
/**
* Replaces the first subsequence of the <tt>source</tt> string that matches
* the literal target string with the specified literal replacement string.
*
* @param source source string on which the replacement is made
* @param target the string to be replaced
* @param replacement the replacement string
* @return the resulting string
*/
private static String replaceFirst2(String source, String target, String replacement) {
int index = source.indexOf(target);
if (index == -1) {
return source;
}
return source.substring(0, index)
.concat(replacement)
.concat(source.substring(index+target.length()));
}
Измерение времени
На основе 10 запусков метод replaceFirst2
выполняется примерно в 5 раз быстрее , чем метод replaceFirst1
. Я поместил оба этих метода в цикл с 100 000 повторений и получил следующие результаты в миллисекундах:
Method Results (in ms) Average
replaceFirst1: 220 187 249 186 199 211 172 199 281 199 | 210
replaceFirst2: 40 39 58 45 48 40 42 42 43 59 | 45