go实现字符串的逆转(reverse)——顺便说,go的语法太爽了

go语言字符串逆转 reverse 方法

package main
import "fmt"
func main() {
s := "foobar"
a := []rune(s)
fmt.Printf("%s\n", s)
fmt.Printf("字符串逆转过程:\n")
for i,j := 0, len(a)-1 ; i < j ; i, j = i+1, j-1 {
a[i],a[j] = a[j], a[i]
fmt.Println(string(a))

}
fmt.Printf("%s\n", string(a)) 
}

输出如下:

C:\Users\asus\Desktop>test.exe
foobar
字符串逆转过程:
roobaf
raobof
raboof
raboof

值得一说的是 a[i],a[j] = a[j], a[i] go里面把它叫做平行赋值。如:
a, b := 20, 16
相当于,a=20, b=16.

:= 的变量声明、赋值也超赞

goto 语句

顺便记记goto语句的用法

for i:=0;i<10;i++{
fmt.Printf("%d\n",i)
}

-------循环语句和goto分割线

i:=0
here:
fmt.Printf("%d\n",i)
i++
if i<10 {
goto here
}

它们两是等价的

猜你喜欢

转载自www.cnblogs.com/famine/p/11973534.html