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"))
}
i'm new at go and programming actually, the output now is A, but why when i change the variable value to "ab" it returns no value it must be "Ab" for the output
CodePudding user response:
So, you basically want all a
s in the input to be changed to A
.
At the moment you just check whether the whole string equals "a"
, and "ab"
isn't equal to "a"
. Therefore, the program ends up with return ""
in the second case.
Normally, you can achieve what you want with something like strings.ReplaceAll("abaaba","a","A")
. But for educational purposes, here's a "manual" solution.
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
}
Also note that c
is of type rune
and therefore must be converted to string
with string(c)
.