i want to generate return string function with looping for some index string

Issue

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

Solution

So, you basically want all as in the input to be changed to A.
At the moment you just check whether the whole string is "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).

Answered By – NotX

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.