How can I iterate over each 2 consecutive characters in a string in go?

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

How can I iterate over each 2 consecutive characters in a string in go?

问题

我有一个像这样的字符串:

package main

import "fmt"

func main() {
    some := "p1k4"

    for i := 0; i < len(some); i += 2 {
        fmt.Print(string(some[i]), string(some[(i+1)%len(some)]), ", ")
    }
}

我想要获取字符串中每两个连续的字符并将它们打印出来。输出应该是p1, 1k, k4, 4p

我已经尝试过,但仍然无法找到答案。请问我应该如何编写这段代码以获得我想要的输出?

英文:

I have a string like this:

package main

import &quot;fmt&quot;

func main() {
    some := &quot;p1k4&quot;

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

I want take each two consecutive characters in the string and print them. 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?

答案1

得分: 9

Go将字符串存储在内存中作为它们的UTF-8编码字节序列。这将ASCII字符一对一地映射到字节,但是超出该范围的字符将映射到多个字节。

因此,我建议使用for range循环遍历字符串,该循环遍历字符串的符文(字符),正确解码多字节符文。这样做的优点是它不需要分配内存(与将string转换为[]rune不同)。您还可以使用fmt.Printf("%c%c", char1, char2)打印这些对,这也不需要分配内存(与将rune转换回string并连接它们不同)。

要了解有关Go中的字符串、字符和符文的更多信息,请阅读博文:Go中的字符串、字节、符文和字符

由于循环仅返回迭代中的“当前”符文(而不是前一个或下一个符文),请使用另一个变量来存储前一个(和第一个)符文,以便在打印时可以访问它们。

让我们编写一个按您要求打印对的函数:

func printPairs(s string) {
    var first, prev rune

    for i, r := range s {
        if i == 0 {
            first, prev = r, r
            continue
        }
        fmt.Printf("%c%c, ", prev, r)
        prev = r
    }

    // 打印最后一对:prev是最后一个符文
    fmt.Printf("%c%c\n", prev, first)
}

使用您的输入和另一个具有多字节符文的字符串进行测试:

printPairs("p1k4")
printPairs("Go-世界")

输出将是(在Go Playground上尝试一下):

p1, 1k, k4, 4p
Go, o-, -世, 世界, 界G
英文:

Go stores strings in memory as their UTF-8 encoded byte sequence. This maps ASCII charactes one-to-one in bytes, but characters outside of that range map to multiple bytes.

So I would advise to use the for range loop over a string, which ranges over the runes (characters) of the string, properly decoding multi-byte runes. This has the advantage that it does not require allocation (unlike converting the string to []rune). You may also print the pairs using fmt.Printf(&quot;%c%c&quot;, char1, char2), which also will not require allocation (unlike converting runes back to string and concatenating them).

To learn more about strings, characters and runes in Go, read blog post: Strings, bytes, runes and characters in Go

Since the loop only returns the "current" rune in the iteration (but not the previous or the next rune), use another variable to store the previous (and first) runes so you have access to them when printing.

Let's write a function that prints the pairs as you want:

func printPairs(s string) {
	var first, prev rune

	for i, r := range s {
		if i == 0 {
			first, prev = r, r
			continue
		}
		fmt.Printf(&quot;%c%c, &quot;, prev, r)
		prev = r
	}

	// Print last pair: prev is the last rune
	fmt.Printf(&quot;%c%c\n&quot;, prev, first)
}

Testing it with your input and with another string that has multi-byte runes:

printPairs(&quot;p1k4&quot;)
printPairs(&quot;Go-世界&quot;)

Output will be (try it on the Go Playground):

p1, 1k, k4, 4p
Go, o-, -世, 世界, 界G

答案2

得分: 2

package main

import (
	"fmt"
)

func main() {
	str := "12345"
	for i := 0; i < len(str); i++ {
		fmt.Println(string(str[i]) + string(str[(i+1)%len(str)]))
	}

}

这是一个Go语言的程序,它的功能是将字符串中的每个字符与下一个字符进行拼接,并打印出来。

英文:
package main

import (
	&quot;fmt&quot;
)

func main() {
	str := &quot;12345&quot;
	for i := 0; i &lt; len(str); i++ {
		fmt.Println(string(str[i]) + string(str[(i+1)%len(str)]))
	}

}

答案3

得分: 0

这是一个简单的循环,它遍历你的字符串,并在末尾添加第一个字符:

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

这段代码的功能是将字符串中的每两个字符打印出来。

英文:

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

package main

import &quot;fmt&quot;

func main() {
	some := &quot;p1k4&quot;
	ns := some + string(some[0])
	for i := 0; i &lt; len(ns)-1; i++ {
		fmt.Println(ns[i:i+2])
	}
}

huangapple
  • 本文由 发表于 2022年1月4日 15:27:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/70575283.html
匿名

发表评论

匿名网友

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

确定