object WhitespaceCleaner {
/**
* Removes leading and trailing whitespace and collapses multiple
* consecutive whitespace characters into a single space.
*
* @param input The original string containing extra spaces.
* @return A normalized string with single space separation.
*/
def removeExtraWhitespace(input: String): String = {
Option(input) match {
case Some(str) =>
// Step 1: trim removes leading and trailing whitespace.
// Step 2: replaceAll("""\s+""", " ") matches any contiguous sequence
// of 1 or more whitespace characters and collapses them down to a single space.
str.trim.replaceAll("""\s+""", " ")
case None =>
""
}
}
def main(args: Array[String]): Unit = {
// Input string containing arbitrary whitespace, tabs, and padding
val s = " This is a test string with extra spaces. "
// Clean the string using standard string methods
val cleanedString = removeExtraWhitespace(s)
println(cleanedString)
}
}
/*
run:
This is a test string with extra spaces.
*/