Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, you basically want all as 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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading