其他分享
首页 > 其他分享> > go学习 - 字符串翻转

go学习 - 字符串翻转

作者:互联网

go学习 - 字符串翻转

代码如下,比较low,但能实现:

package go_test_test

import (
	"fmt"
	"testing"
)

/**
 * Created by Goland
 * User: wkk alisleepy@hotmail.com
 * Time: 2022/8/5 - 00:21
 * Desc: <翻转字符串>
 */

func TestReverseStr(t *testing.T) {
	var str, newStr = "abcde", ""
	fmt.Println("origin str:", str)
	newStr = reverse(str)
	fmt.Println("new str:", newStr)
}

// 翻转字符串
// 字符串翻转,先将字符存放在byte切片中,再将byte切片强制类型转换为string
// 字符串本身值不可变,但是可以取值后存放在其他切片中,再将其他切片强制类型转换
func reverse(str string) string {
	length := len(str)
	if length == 0 {
		return ""
	}

	// 声明切片
	var result []byte
	for i := 0; i < length; i++ {
		result = append(result, str[length-i-1])
	}
	return string(result)
}

标签:string,切片,字符串,length,result,str,go,翻转
来源: https://www.cnblogs.com/alisleepy/p/16552773.html