1 回答

TA貢獻1859條經驗 獲得超6個贊
因此,您基本上希望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
}
另請注意cis 類型rune,因此必須轉換為stringwith string(c)。
編輯:如評論中所述,實際上這不是構建新string. rune除了從到轉換的麻煩之外string,string每次我們添加一些東西并刪除舊的東西時,我們都會創建一個新的。相反,我們只想創建string一次 - 在最后,當我們確切知道結果的樣子時string。因此,我們應該改用字符串生成器。為了避免混淆,這里有一個單獨的例子:
func change(a string) string {
var resultBuilder strings.Builder
for _, c := range a { // loop over all characters
if c != 'a' { // in case it's not an "a" ...
resultBuilder.WriteRune(c) // ... just append it to the new string v
} else {
resultBuilder.WriteString("A") // otherwise append an "A" to the new string v
}
}
return resultBuilder.String() // Create the final string once everything is set
}
- 1 回答
- 0 關注
- 129 瀏覽
添加回答
舉報