gpt4 book ai didi

string - 在循环中更新字符串值

转载 作者:数据小太阳 更新时间:2023-10-29 03:30:39 24 4
gpt4 key购买 nike

是否可以在执行 for 循环时更新字符串的值?

package main 
import (
"fmt"
"strings"
)

func Chop(r int, s string) string {
return s[r:]
}

func main() {
s:= "ThisIsAstring1ThisIsAstring2ThisIsAstring3"
for strings.Contains(s, "string") {
// Original value > ThisIsAstring1ThisIsAstring2ThisIsAstring3
fmt.Println(s)
// I delete a part of the string > ThisIsAstring1
remove := len(s)/3
// Now, I update the value of string > string := ThisIsAstring2ThisIsAstring3
s := Chop(remove, s)
fmt.Println(s)
break
}
}

我不知道怎么做。

最佳答案

我不知道用例是什么,但可以了。让我们从识别代码中的问题开始:

// You cannot use a reserved keyword "string" as a variable name
string:= "ThisIsAstring1ThisIsAstring2ThisIsAstring3"
for strings.Contains(string, "string") {
// Remove is a float, but you need to pass an int into your chop function
remove := len(string)/3
// You're reassigning your string variable. You really just want =, not :=
string := Chop(remove, string)
fmt.Println(string)
}

现在,这里有一个适用于您的用例的解决方案:

str := "ThisIsAstring1ThisIsAstring2ThisIsAstring3"
for strings.Contains(str, "string") {
fmt.Println(str)
remove := int(len(str) / 3)
str = Chop(remove, str)
}
fmt.Println(str)

去玩: https://play.golang.org/p/NdROIFDS_5

关于string - 在循环中更新字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43922734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com