同时遍历两个字符串

huangapple go评论97阅读模式
英文:

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]))
}
英文:

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 &lt; len(string_1); i++ {
	fmt.Println(string(ascii_runes[i]) + string(shifted_runes[i]))
}

答案1

得分: 4

不确定我是否理解正确,但是举个例子:

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])
        }
}

也可以在这里查看:http://play.golang.org/p/2ruvLFg_qe


输出:

sS
tT
rR
iI
nN
gG
1!
英文:

Not sure IIUC, but for example:

package main

import (
        &quot;fmt&quot;
)

var (
        ascii	= []rune(&quot;string1&quot;)
        shifted	= []rune(&quot;STRING!&quot;)
)

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

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


Output:

sS
tT
rR
iI
nN
gG
1!

答案2

得分: 2

例如,

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]))
    }
}

输出:

ss
tt
rr
ii
nn
gg
__
12
英文:

For example,

package main

import &quot;fmt&quot;

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

Output:

ss
tt
rr
ii
nn
gg
__
12

答案3

得分: 0

不是特别漂亮,但是一种高效的方法是使用strings.NewReader和它的ReadRune方法。

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 }
  }
}
英文:

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 &lt; rune2 }
  }
}

huangapple
  • 本文由 发表于 2012年10月29日 19:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/13120961.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定