golang – Replacing string characters by numbers golang

huangapple go评论101阅读模式
英文:

golang - Replacing string characters by numbers golang

问题

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

// 获取一个介于0和字符串长度-1之间的位置,用于插入一个随机数
position := rand.Intn(count - 1)
fmt.Println("Going to change the position number: ", position)
// 在指定位置插入一个介于[0-9]之间的随机数
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

有人可以帮我在所需的字符串位置插入这个数字吗?我没有找到任何类似的案例。

提前感谢。

英文:

I'm trying to run this piece of code to replace a character of a string by a random number:

//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:]

When this is executed, the output is:

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

Could anyone help me about inserting that number inside the desired string position? I didn't find any duplicate case of this.

Thanks in advance.

答案1

得分: 3

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

string('0' + rand.Intn(10))
英文:

There are no printable characters in the range [0, 9). If you want an ascii value, start at 48 ('0'). You probably want to include 9 too, so use rand.Intn(10)

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

huangapple
  • 本文由 发表于 2017年5月24日 02:14:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/44142182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定