英文:
Convert normal space/whitespace to non-breaking space?
问题
这是一个简单的问题,但我仍然无法弄清楚如何做到。
假设我有这个字符串:
x := "this string"
在'this'和'string'之间的空格默认为常规的Unicode空格字符32/U+0020
。如何将其转换为Go中的不间断Unicode空格字符U+00A0
?
英文:
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?
答案1
得分: 4
使用文档来识别标准的strings
包作为一个可能的候选项,然后搜索它(或者阅读它的全部内容,你应该知道在任何你使用的语言的标准库/包中都有什么可用的)来找到strings.Map
。
然后,将任何空白字符转换为非断行空格的明显简短的解决方案如下:
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\n", result)
}
如前所述,如果你真的只想替换" "
,那么可以使用strings.Replace
。
英文:
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\n", result)
}
As previously mentioned, if you really only want to replace " "
then perhaps strings.Replace
.
答案2
得分: -1
我认为一种基本的方法是创建一个简单的函数:
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"))
}
如果你需要更高级的操作,你可以使用以下内容创建一些东西:
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
阅读 http://blog.golang.org/normalization 以获取有关如何使用它的更多信息。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论