object removeLastNOccurrencesProgram {
// Remove last n occurrences of a substring
def removeLastNOccurrences(s: String, sub: String, n: Int): String = {
val positions = collection.mutable.ListBuffer[Int]()
var pos = s.indexOf(sub)
var offset = 0
// Find all occurrences
while (pos != -1) {
positions += pos
offset = pos + sub.length
pos = s.indexOf(sub, offset)
}
// Remove from the end
positions.reverse.take(n).foldLeft(s) { (acc, start) =>
acc.substring(0, start) + acc.substring(start + sub.length)
}
}
// Remove extra spaces (collapse multiple spaces, trim ends)
def removeExtraSpaces(s: String): String =
s.trim.split("\\s+").mkString(" ")
def main(args: Array[String]): Unit = {
val text = "abc xyz xyz abc xyzabcxyz abc"
val result = removeLastNOccurrences(text, "xyz", 3)
println(result)
val cleaned = removeExtraSpaces(result)
println(cleaned)
}
}
/*
run:
abc xyz abc abc abc
abc xyz abc abc abc
*/