Go中字符串的遍历

Python018

Go中字符串的遍历,第1张

首先说一下go中的字符串类型:

字符串就是一串固定长度的字符连接起来的字符序列。Go的字符串是由单个字节连接起来的。Go语言的字符串的字节使用UTF-8编码标识Unicode文本。

下面介绍字符串的三种遍历方式,根据实际情况选择即可。

该遍历方式==缺点==:遍历是按照字节遍历,因此如果有中文等非英文字符,就会出现乱码,比如要遍历"abc北京"这个字符串,效果如下:

可见这不是我们想要的效果,根据utf-8中文编码规则,我们要str[3]str[4]str[5]三个字节合起来组成“北”字及 str[6]str[7]str[8]合起来组成“京”字。由此引出下面第二种遍历方法。

该方式是按照字符遍历的,所以不会出现乱码,如下:

运行结果:

从图中可以看到第二个汉子“京”的开始下标是6,直接跳过了4和5,可见确实依照utf8编码方式将三个字节组合成了一个汉字,str[3]-str[5]组合成“北”字,str[6]-str[8]组合成了“京”字。

由于下标的不确定性,所以引出了下面的遍历方式。

1 可以先将字符串转成 []rune 切片

2 再用常规方法进行遍历

运行效果:

由此可见下标是按1递增的,没有产生跳跃现象。

go语言的字符串是UTF-8编码的、不可改变的字节序列。

要修改字符串,只能以原串为基础,创建一个新串。下面的图中是一个参考示例,提供了以原串为蓝本,创建新串的两种方法。

代码

输出

按值传递函数参数,是拷贝参数的实际值到函数的形式参数的方法调用。在这种情况下,参数在函数内变化对参数不会有影响。

默认情况下,Go编程语言使用调用通过值的方法来传递参数。在一般情况下,这意味着,在函数内码不能改变用来调用所述函数的参数。考虑函数swap()的定义如下。

代码如下:

/* function definition to swap the values */

func swap(int x, int y) int {

var temp int

temp = x /* save the value of x */

x = y/* put y into x */

y = temp /* put temp into y */

return temp

}

现在,让我们通过使实际值作为在以下示例调用函数swap():

代码如下:

package main

import "fmt"

func main() {

/* local variable definition */

var a int = 100

var b int = 200

fmt.Printf("Before swap, value of a : %d\n", a )

fmt.Printf("Before swap, value of b : %d\n", b )

/* calling a function to swap the values */

swap(a, b)

fmt.Printf("After swap, value of a : %d\n", a )

fmt.Printf("After swap, value of b : %d\n", b )

}

func swap(x, y int) int {

var temp int

temp = x /* save the value of x */

x = y/* put y into x */

y = temp /* put temp into y */

return temp

}

让我们把上面的代码放在一个C文件,编译并执行它,它会产生以下结果:

Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :100

After swap, value of b :200

这表明,参数值没有被改变,虽然它们已经在函数内部改变。

通过传递函数参数,即是拷贝参数的地址到形式参数的参考方法调用。在函数内部,地址是访问调用中使用的实际参数。这意味着,对参数的更改会影响传递的参数。

要通过引用传递的值,参数的指针被传递给函数就像任何其他的值。所以,相应的,需要声明函数的参数为指针类型如下面的函数swap(),它的交换两个整型变量的值指向它的参数。

代码如下:

/* function definition to swap the values */

func swap(x *int, y *int) {

var temp int

temp = *x/* save the value at address x */

*x = *y /* put y into x */

*y = temp/* put temp into y */

}

现在,让我们调用函数swap()通过引用作为在下面的示例中传递数值:

代码如下:

package main

import "fmt"

func main() {

/* local variable definition */

var a int = 100

var b int= 200

fmt.Printf("Before swap, value of a : %d\n", a )

fmt.Printf("Before swap, value of b : %d\n", b )

/* calling a function to swap the values.

* &a indicates pointer to a ie. address of variable a and

* &b indicates pointer to b ie. address of variable b.

*/

swap(&a, &b)

fmt.Printf("After swap, value of a : %d\n", a )

fmt.Printf("After swap, value of b : %d\n", b )

}

func swap(x *int, y *int) {

var temp int

temp = *x/* save the value at address x */

*x = *y/* put y into x */

*y = temp/* put temp into y */

}

让我们把上面的代码放在一个C文件,编译并执行它,它会产生以下结果:

Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :200

After swap, value of b :100

这表明变化的功能以及不同于通过值调用的外部体现的改变不能反映函数之外。