如何从golang中的字符串获取单个Unicode字符 [英] How to get a single unicode-character from string in golang

查看:1406
本文介绍了如何从golang中的字符串获取单个Unicode字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是golang的开端。我想知道如何从一个字符串中得到一个unicode字符。例如,字符串是你好,我怎样才能得到第一个字符你?
从其他地方我得到一种方式:


  var str =你好
runes_array:= []符文(str)
fmt.Println(字符串(runes_array [0]))

确实有效。

但是我仍然有一些疑问:

1)有没有其他的方法可以做到?

2)为什么在golang中不能使用str [0]从字符串中获取unicode字符,

,但是获取字节数据?

解决方案

首先,您可能想阅读 https://blog.golang.org/strings
它将回答您的部分问题。



Go中的字符串可以包含任意字节。当你写str [i]时,结果是一个字节,并且索引总是一个字节数。

大多数时候,字符串都是用UTF- 8但是。你有多种方式来处理字符串中的UTF-8编码。

例如,你可以使用for ... range语句在一个字符串符号上迭代符文。

  var第一个符文
代表_,c:=代码str {
first = c
break

//现在包含字符串的第一个符号

你也可以利用unicode / utf8包。例如:

  r,size:= utf8.DecodeRuneInString(str)
// r包含第一个符文字符串
//大小是以字节为单位的符文大小

如果字符串是以UTF-8编码,没有直接访问字符串的第n个符号的方法,因为符文的大小(以字节为单位)不是恒定的。如果你需要这个特性,你可以很容易地编写你自己的帮助函数来完成它(使用for ... range,或者使用unicode / utf8包)。


I am a beginer of golang.I wonder that how I can I get a unicode character from a string.
Like ,the string is "你好",how can I get the first character "你"?
From other place I get one way:

var str="你好"
runes_array := []rune(str)
fmt.Println(string(runes_array[0]))

It does work.
But I still have some questions:
1) Is there another way to make it?
2) Why in golang cannot use str[0] to get unicode character from string,
    but get byte data?

解决方案

First, you may want to read https://blog.golang.org/strings It will answer part of your questions.

A string in Go can contains arbitrary bytes. When you write str[i], the result is a byte, and the index is always a number of bytes.

Most of the time, strings are encoded in UTF-8 though. You have multiple ways to deal with UTF-8 encoding in a string.

For instance, you can use the for...range statement to iterate on a string rune by rune.

var first rune
for _,c := range str {
    first = c
    break
}
// first now contains the first rune of the string

You can also leverage the unicode/utf8 package. For instance:

r, size := utf8.DecodeRuneInString(str)
// r contains the first rune of the string
// size is the size of the rune in bytes

If the string is encoded in UTF-8, there is no direct way to access the nth rune of the string, because the size of the runes (in bytes) is not constant. If you need this feature, you can easily write your own helper function to do it (with for...range, or with the unicode/utf8 package).

这篇关于如何从golang中的字符串获取单个Unicode字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆