问题描述

有人知道如何在Golang中按长度分割字符串吗?

Does anyone know how to split a string in Golang by length?

例如,每隔3个字符分割一次"helloworld",因此理想情况下应返回"hel","low","orl","d"的数组?

For example to split "helloworld" after every 3 characters, so it should ideally return an array of "hel" "low" "orl" "d"?

或者,一种可能的解决方案是在每3个字符后也添加一个换行符.

Alternatively a possible solution would be to also append a newline after every 3 characters..

所有想法都将不胜感激!

All ideas are greatly appreciated!

推荐答案

请确保,将您的字符串切成一片符文:请参阅"将字符串切成字母".

Make sure to convert your string into a slice of rune: see "Slice string into letters".

 for  string  rune  string  rune 
forstringrunestringrune
for i, r := range s {
    fmt.Printf("i%d r %c\n", i, r)
    // every 3 i, do something
}
 r [n:n + 3] 
r[n:n+3]
 i 
i
 s:=世间界bcd界efg世" 
s := "世a界世bcd界efg世"

如果您尝试逐字节地解析它,则会丢失(在每3个字符的天真的拆分中)一些索引模3"(等于2、5、8和11),因为索引会增加超过这些值:

If you try to parse it byte by byte, you will miss (in a naive split every 3 chars implementation) some of the "index modulo 3" (equals to 2, 5, 8 and 11), because the index will increase past those values:

for i, r := range s {
    res = res + string(r)
    fmt.Printf("i %d r %c\n", i, r)
    if i > 0 && (i+1)%3 == 0 {
        fmt.Printf("=>(%d) '%v'\n", i, res)
        res = ""
    }
}

输出:

i  0 r 世
i  3 r a   <== miss i==2
i  4 r 界
i  7 r 世  <== miss i==5
i 10 r b  <== miss i==8
i 11 r c  ===============> would print '世a界世bc', not exactly '3 chars'!
i 12 r d
i 13 r 界
i 16 r e  <== miss i==14
i 17 r f  ===============> would print 'd界ef'
i 18 r g
i 19 r 世 <== miss the rest of the string
 a:= [] rune(s)
a := []rune(s)
for i, r := range a {
    res = res + string(r)
    fmt.Printf("i%d r %c\n", i, r)
    if i > 0 && (i+1)%3 == 0 {
        fmt.Printf("=>(%d) '%v'\n", i, res)
        res = ""
    }
}

输出:

i 0 r 世
i 1 r a
i 2 r 界 ===============> would print '世a界'
i 3 r 世
i 4 r b
i 5 r c ===============> would print '世bc'
i 6 r d
i 7 r 界
i 8 r e ===============> would print 'd界e'
i 9 r f
i10 r g
i11 r 世 ===============> would print 'fg世'

这篇关于在Golang中按长度拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!