在Golang中将正常空间/空白转换为不间断空间?

This is a simple question, but I still can't figure out how to do it.

Say I have this string:

x := "this string"

The whitespace between 'this' and 'string' defaults to the regular unicode whitespace character 32/U+0020. How would I convert it into the non-breaking unicode whitespace character U+00A0 in Go?

I think a basic way to do it is by creating a simple function:

http://play.golang.org/p/YT8Cf917il

package main

import "fmt"

func ReplaceSpace(s string) string {
    var result []rune
    const badSpace = '\u0020'
    for _, r := range s {
        if r == badSpace {
            result = append(result, '\u00A0')
            continue
        }
        result = append(result, r)
    }
    return string(result)
}

func main() {
    fmt.Println(ReplaceSpace("this string"))
}

If you need more advanced manipulations you could create something with

"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"

Read http://blog.golang.org/normalization for more information on how to use it

Use the documentation to identify the standard strings package as a likely candidate, and then search it (or read through it all, you should know what's available in the standard library/packages of any language you use) to find strings.Map.

Then the obvious short simple solution to convert any white space would be:

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func main() {
    const nbsp = '\u00A0'
    result := strings.Map(func(r rune) rune {
        if unicode.IsSpace(r) {
            return nbsp
        }
        return r
    }, "this string")

    fmt.Printf("%s → %[1]q
", result)
}

Playground

As previously mentioned, if you really only want to replace " " then perhaps strings.Replace.