编写一个针对 Unicode 字母的 toUpper 函数。

huangapple go评论87阅读模式
英文:

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 &#39;a&#39; &lt;= b &amp;&amp; b &lt;= &#39;z&#39; {
            p[i] = b + &#39;A&#39; - &#39;a&#39;
        }
    }
}

func main() {
    pathName := path(&quot;/usr/bin/tso&quot;)
    pathName.ToUpper()
    string1 := string(pathName)
    fmt.Printf(&quot;%s\n&quot;, 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 (
    &quot;unicode&quot;
    &quot;fmt&quot;
)

type path []rune

func (p path) ToUpper() {
    for i, b := range p {
        p[i] = unicode.ToUpper(b)
    }
}

func main() {
    pathName := path(&quot;/usr/bin/tso&quot;)
    pathName.ToUpper()
    string1 := string(pathName)
    fmt.Printf(&quot;%s\n&quot;, 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 (
	&quot;fmt&quot;
	&quot;strings&quot;
	&quot;unicode&quot;
)

func main() {
	pathName := strings.Map(unicode.ToUpper, &quot;/usr/bin/tso&quot;)
	fmt.Printf(&quot;%s\n&quot;, pathName)
}

huangapple
  • 本文由 发表于 2015年3月23日 11:29:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/29202849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定