fn remove_last_n_occurrences(mut s: String, sub: &str, mut n: usize) -> String {
let mut positions = Vec::new();
let mut start = 0;
// Find all occurrences
while let Some(pos) = s[start..].find(sub) {
let abs_pos = start + pos;
positions.push(abs_pos);
start = abs_pos + sub.len();
}
// Remove from the end
for &pos in positions.iter().rev() {
if n == 0 {
break;
}
let end = pos + sub.len();
s = format!("{}{}", &s[..pos], &s[end..]);
n -= 1;
}
s
}
fn remove_extra_spaces(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn main() {
let text = "abc xyz xyz abc xyzabcxyz abc".to_string();
let result = remove_last_n_occurrences(text, "xyz", 3);
println!("{}", result);
let cleaned = remove_extra_spaces(&result);
println!("{}", cleaned);
}
/*
run:
abc xyz abc abc abc
abc xyz abc abc abc
*/