在循环中更新字符串值

ica*_*ajo -1 string for-loop go

我们执行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
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道怎么做.

wil*_*.09 5

我不知道用例是什么,但是这里有.让我们从识别代码中的问题开始:

// 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)
}
Run Code Online (Sandbox Code Playgroud)

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

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

GoPlay:https: //play.golang.org/p/NdROIFDS_5