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:

  1. 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.

  1. Define the main function:
func main() {
    // code goes here
}

The main function is the entry point of the program.

  1. Define the input string:
str := "Hello     world!     How    are   you?"

The input string contains multiple spaces between words.

  1. Create a regular expression pattern to match multiple spaces:
re := regexp.MustCompile(`\s+`)

The regular expression pattern \s+ matches one or more whitespace characters.

  1. 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.

  1. Print the result:
fmt.Println(result)

The result, with multiple spaces replaced by a single space, is printed to the console.