为什么在反转字符串时这些字符不显示?

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

Why wont these chars show when reversing string?

问题

我只会翻译文本内容,不会执行代码。以下是您提供的代码的翻译:

我只是想知道为什么当我反转并打印字符串中的每个字符时,这些亚洲字符不会显示出来。

package main

import "fmt"

func main() {

        a := "The quick brown 狐 jumped over the lazy 犬"
        var length int = len(a) - 1

        for ; length > -1; length-- {

                 fmt.Printf("%c", a[length])
        }
        fmt.Println()
}
英文:

I'm just wondering why these asian characters in this string wont show up when I reverse and print the individual characters in the string.

package main

import "fmt"

func main() {

        a := "The quick brown 狐 jumped over the lazy 犬"
        var lenght int = len(a) - 1

        for ; lenght > -1; lenght-- {

                 fmt.Printf("%c", a[lenght])
        }
        fmt.Println()
}

答案1

得分: 5

你正在通过字节而不是“逻辑字符”访问字符串数组。
为了更好地理解这个例子,首先将字符串作为一个符文数组分割,然后倒序打印符文。

package main

import "fmt"

func main() {
    msg := "The quick brown 狐 jumped over the lazy 犬"

    elements := make([]rune, 0)

    for _, rune := range msg {
        elements = append(elements, rune)
    }

    for i := len(elements) - 1; i >= 0; i-- {
        fmt.Println(string(elements[i]))
    }
}

更简洁的版本:http://play.golang.org/p/PYsduB4Rgq

package main

import "fmt"

func main() {
    msg := "The quick brown 狐 jumped over the lazy 犬"

    elements := []rune(msg)

    for i := len(elements) - 1; i >= 0; i-- {
        fmt.Println(string(elements[i]))
    }
}
英文:

You are accessing the string array by byte not by 'logical character'
To better understand this example breaks the string first as an array of runes and then prints the rune backwards.

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

package main

import "fmt"

func main() {
	msg := "The quick brown 狐 jumped over the lazy 犬"

	elements := make([]rune, 0)

	for _, rune := range msg {
		elements = append(elements, rune)
	}

	for i := len(elements) - 1; i >= 0; i-- {
		fmt.Println(string(elements[i]))
	}
}

Shorter Version: http://play.golang.org/p/PYsduB4Rgq

package main

import "fmt"

func main() {
	msg := "The quick brown 狐 jumped over the lazy 犬"

	elements := []rune(msg)

	for i := len(elements) - 1; i >= 0; i-- {
		fmt.Println(string(elements[i]))
	}
}

huangapple
  • 本文由 发表于 2014年6月19日 08:06:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/24296870.html
匿名

发表评论

匿名网友

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

确定