Ошибки при попытке удалить нужный подтекст из текста java
Код работает, пока не столкнется с двумя одинаковыми подтекстами в самом тексте. Суть кода в том, что он должен удалить все найденные подтексты и вывести отфильтрованный. В данном случае очистить текст от всех "qwerty" Если ввести qwertyqwerty...text...qwerty выдает ошибки. Я пробовал создавать другие дополнительные StringBuffer которые уже изменял, не помогло
public static void main(String[] args) {
StringBuffer text = new StringBuffer("qwertyqwerty");//ошибка
Pattern pattern = Pattern.compile("qwerty", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
int shift = 0;
while (matcher.find()) {
text.delete(matcher.start() - shift, matcher.end() - shift);
shift+= matcher.end() - matcher.start();
}
System.out.println(text);
}
}
Ответы (2 шт):
Автор решения: unwx
→ Ссылка
public static void main(String[] args) {
StringBuffer text = new StringBuffer("qwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyQWERTYtext : hello worldqwerty");
Pattern pattern = Pattern.compile("qwerty", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
int p = 0;
while (matcher.find(p)) {
p = matcher.start();
text.delete(matcher.start(), matcher.end());
}
System.out.println(text);
}
}
//text : hello world
Process finished with exit code 0