英文:
Writing a toUpper function for unicode letters
问题
从这里开始http://blog.golang.org/slices(就在Capacity部分之前)
type path []byte
func (p path) ToUpper() {
for i, b := range p {
if 'a' <= b && b <= 'z' {
p[i] = b + 'A' - 'a'
}
}
}
func main() {
pathName := path("/usr/bin/tso")
pathName.ToUpper()
string1 := string(pathName)
fmt.Printf("%s\n", string1)
}
在学习Golang的切片和相关内容时,我看到了这个函数用于转换ASCII字符。你如何修改这个函数以处理Unicode字符呢?
英文:
From here http://blog.golang.org/slices (it's right before the Capacity section)
type path []byte
func (p path) ToUpper() {
for i, b := range p {
if 'a' <= b && b <= 'z' {
p[i] = b + 'A' - 'a'
}
}
}
func main() {
pathName := path("/usr/bin/tso")
pathName.ToUpper()
string1 := string(pathName)
fmt.Printf("%s\n", string1)
}
Was reading on slices and stuff in golang. This is a function to convert ascii characters. How would you go about turning this function to handle unicode as well?
答案1
得分: 6
你在使用 Unicode 时应该使用 rune
。Golang 中的 unicode
包有一个 ToUpper
函数。
package main
import (
"unicode"
"fmt"
)
type path []rune
func (p path) ToUpper() {
for i, b := range p {
p[i] = unicode.ToUpper(b)
}
}
func main() {
pathName := path("/usr/bin/tso")
pathName.ToUpper()
string1 := string(pathName)
fmt.Printf("%s\n", string1)
}
在 playground 上查看示例:example
英文:
You should use rune
when you use unicode. The unicode
package in golang has a toUpper function.
package main
import (
"unicode"
"fmt"
)
type path []rune
func (p path) ToUpper() {
for i, b := range p {
p[i] = unicode.ToUpper(b)
}
}
func main() {
pathName := path("/usr/bin/tso")
pathName.ToUpper()
string1 := string(pathName)
fmt.Printf("%s\n", string1)
}
in the playground:
example
答案2
得分: 1
你可以使用strings.Map
函数将一个函数应用于字符串的每个字符,并返回映射后的字符串。以下是示例代码的Playground链接:
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
pathName := strings.Map(unicode.ToUpper, "/usr/bin/tso")
fmt.Printf("%s\n", pathName)
}
英文:
You can use strings.Map
to apply a function to each rune of a string, returning the mapped string. Playground link to this code:
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
pathName := strings.Map(unicode.ToUpper, "/usr/bin/tso")
fmt.Printf("%s\n", pathName)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论