go in a string, replace multiple spaces with single space
package main
import (
"fmt"
"regexp"
)
func main() {
str := "Hello world! How are you?"
re := regexp.MustCompile(`\s+`)
result := re.ReplaceAllString(str, " ")
fmt.Println(result)
}
Explanation:
- Import the necessary packages:
import (
"fmt"
"regexp"
)
The fmt
package is used for printing the result, and the regexp
package is used for regular expression matching and replacement.
- Define the main function:
func main() {
// code goes here
}
The main function is the entry point of the program.
- Define the input string:
str := "Hello world! How are you?"
The input string contains multiple spaces between words.
- Create a regular expression pattern to match multiple spaces:
re := regexp.MustCompile(`\s+`)
The regular expression pattern \s+
matches one or more whitespace characters.
- Replace the multiple spaces with a single space:
result := re.ReplaceAllString(str, " ")
The ReplaceAllString
function of the regexp
package is used to replace all occurrences of the pattern with the replacement string.
- Print the result:
fmt.Println(result)
The result, with multiple spaces replaced by a single space, is printed to the console.