ceth
ceth

Reputation: 45295

Iterate over two strings at the same time

I am just wondering if there is any beautiful way to iterate over two strings at the same time:

var ascii_runes = []rune(string_1)
var shifted_runes = []rune(string_2)

for i := 0; i < len(string_1); i++ {
    fmt.Println(string(ascii_runes[i]) + string(shifted_runes[i]))
}

Upvotes: 3

Views: 2035

Answers (3)

Hafthor
Hafthor

Reputation: 16906

Not particularly beautiful, but an efficient way is to use strings.NewReader and its ReadRune method.

func Less(s1, s2 string) bool {
  rdr1 := strings.NewReader(s1)
  rdr2 := strings.NewReader(s2)
  for {
    rune1, _, err1 := rdr1.ReadRune()
    rune2, _, err2 := rdr2.ReadRune()
    if err2 == io.EOF { return false }
    if err1 == io.EOF { return true }
    if rune1 != rune2 { return rune1 < rune2 }
  }
}

Upvotes: 0

peterSO
peterSO

Reputation: 166596

For example,

package main

import "fmt"

func main() {
    var runes_1, runes_2 = []rune("string_1"), []rune("string_2")
    for i := 0; i < len(runes_1) && i < len(runes_2); i++ {
        fmt.Println(string(runes_1[i]) + string(runes_2[i]))
    }
}

Output:

ss
tt
rr
ii
nn
gg
__
12

Upvotes: 2

zzzz
zzzz

Reputation: 91253

Not sure IIUC, but for example:

package main

import (
        "fmt"
)

var (
        ascii   = []rune("string1")
        shifted = []rune("STRING!")
)

func main() {
        for i, v := range ascii {
                fmt.Printf("%c%c\n", v, shifted[i])
        }
}

Also here: http://play.golang.org/p/2ruvLFg_qe


Output:

sS
tT
rR
iI
nN
gG
1!

Upvotes: 4

Related Questions