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

How can I iterate over a string in go?

i have string like this:

package main

import "fmt"

func main() {
    some := "p1k4"

    for i, j := range some {
            fmt.Println()
    }
}

i want take each two string there should curent string then next one, next iteration should get the previous character. the output should like p1, 1k, k4, 4p.

i have tried it and still having trouble finding the answer, how should i write the code in go and get the output i want?

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

>Solution :

This is a simple for loop over your string with the first character appended at the back:

package main

import "fmt"

func main() {
    some := "p1k4"
    ns := some + string(some[0])
    for i := 0; i < len(ns)-1; i++ {
        fmt.Println(ns[i:i+2])
    }
}
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