func change(a string) string {
// fmt.Println(a)
v := ""
if string(a) == "a" {
return "A"
v = a
}
return ""
}
func main() {
fmt.Println(change("a"))
fmt.Println(change("ab"))
}
我是 Go 和編程的新手,現在的輸出是 A,但是為什么當我將變數值更改為“ab”時它沒有回傳任何值,輸出必須是“Ab”
uj5u.com熱心網友回復:
因此,您基本上希望a將輸入中的所有 s 更改為A. 目前,您只需檢查整個字串是否等于"a","ab"不等于"a"。因此,程式以return ""第二種情況結束。
通常,您可以使用strings.ReplaceAll("abaaba","a","A"). 但出于教育目的,這里有一個“手動”解決方案。
func change(a string) string {
v := "" // our new string, we construct it step by step
for _, c := range a { // loop over all characters
if c != 'a' { // in case it's not an "a" ...
v = string(c) // ... just append it to the new string v
} else {
v = "A" // otherwise append an "A" to the new string v
}
}
return v
}
另請注意,c是型別rune,因此必須轉換為stringwith string(c)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530851.html
標籤:去
