【问题标题】:golang - Replacing string characters by numbers golanggolang - 用数字替换字符串字符 golang
【发布时间】:2017-10-23 20:12:16
【问题描述】:

我正在尝试运行这段代码来用随机数替换字符串中的一个字符:

//Get the position between 0 and the length of the string-1  to insert a random number
    position := rand.Intn(count - 1)
    strings.Replace(RandomString,)

    fmt.Println("Going to change the position number: ", position)
    //Insert a random number between [0-9] in the position
    RandomString = RandomString[:position] + string(rand.Intn(9)) + RandomString[position+1:]

执行此操作时,输出为:

I was going to generate..  ljFsrPaUvmxZFFw
Going to change the position number:  2
Random string:  lsrPaUvmxZFFw

谁能帮我把那个数字插入到所需的字符串位置?我没有发现任何重复的案例。

提前致谢。

【问题讨论】:

  • 您需要使用strconv包将rand.Intn(9)转换为实际的字符串值。
  • 完成。我怎么不记得了? :facepalm:
  • 请记住,在幕后,string 只是[]byte。当您尝试将 int 转换为 string 时,它只是获取原始数字 2(不是字符)并尝试将其显示为 unicode。
  • 是的,需要更多地使用 go 的 unicode 包才能更好地理解这一点,感谢您的快速帮助:)

标签: string go random


【解决方案1】:

[0, 9) 范围内没有可打印的字符。如果您想要一个 ascii 值,请从 48 ('0') 开始。你可能也想包含 9,所以使用rand.Intn(10)

string('0' + rand.Intn(10))

【讨论】:

  • 感谢您的回答!如果使用 Itoa 或这个,不确定哪个快!
  • @DavidBarranco:Itoa 做了更多的工作,所以这本质上会更快,而不是在字符串操作的上下文中它真的很重要。
  • 感谢提示,终于用这种方式添加了。最好的问候!
猜你喜欢
  • 2022-01-12
  • 1970-01-01
  • 2023-02-20
  • 2022-12-03
  • 1970-01-01
  • 2016-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多