如何在golang中从一个rune字符串中获取子字符串?

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

How to get a substring from a string of runes in golang?

问题

我找到了这个链接:https://groups.google.com/forum/#!topic/golang-nuts/YyKlLwuWt3w,但据我所知,这些解决方案对我来说都不起作用。

如果你使用将字符串视为切片的方法(str[:20]),它会在字符的中间断开,我们得到的是"ال�"。

编辑:我相信我可以编写一个函数,并将其作为3的倍数来处理,因为runes是int32(32位/(8位/字节))。首先,我需要检查是否存在runes。

英文:

I found this, https://groups.google.com/forum/#!topic/golang-nuts/YyKlLwuWt3w but as far as I can tell, the solutions didn't work for me.

If you use the method of treating a string as a slice(str[:20]), it breaks off in the middle of characters and we get "ال�".

Edit: I believe I could write a function and do it as a multiple of 3's as runes are int32 (32bits/(8bits/byte)). I would first have to check if there are runes.

答案1

得分: 32

只需先将其转换为符文切片,然后切片,最后将结果转换回来:

string([]rune(str)[:20])
英文:

Just convert it to a slice of runes first, slice, then convert the result back:

string([]rune(str)[:20])

答案2

得分: 13

你可以在不分配额外内存的情况下获取一个UTF-8字符串的子串(无需将其转换为rune切片):

func substring(s string, start int, end int) string {
    start_str_idx := 0
    i := 0
    for j := range s {
        if i == start {
            start_str_idx = j
        }
        if i == end {
            return s[start_str_idx:j]
        }
        i++
    }
    return s[start_str_idx:]
}

func main() {
    s := "世界 Hello"
    fmt.Println(substring(s, 0, 1)) // 世
    fmt.Println(substring(s, 1, 5)) // 界 He
    fmt.Println(substring(s, 3, 8)) // Hello
}

这段代码可以获取指定索引范围内的子串。函数substring接受三个参数:原始字符串s、起始索引start和结束索引end。它使用range迭代字符串s,并根据索引值来确定子串的起始和结束位置。最后,它返回指定范围内的子串。在main函数中,我们演示了如何使用substring函数来获取不同范围的子串。

英文:

You can get a substring of a UTF-8 string without allocating additional memory (you don't have to convert it to a rune slice):

<!-- language: lang-go -->

func substring(s string, start int, end int) string {
    start_str_idx := 0
    i := 0
    for j := range s {
        if i == start {
            start_str_idx = j
        }
        if i == end {
            return s[start_str_idx:j]
        }
        i++
    }
    return s[start_str_idx:]
}

func main() {
    s := &quot;世界 Hello&quot;
    fmt.Println(substring(s, 0, 1)) // 世
    fmt.Println(substring(s, 1, 5)) // 界 He
    fmt.Println(substring(s, 3, 8)) // Hello
}

答案3

得分: 3

这是基于字符数的实现,使用了rune技巧:

func substr(input string, start int, length int) string {
    asRunes := []rune(input)
    
    if start >= len(asRunes) {
        return ""
    }
    
    if start+length > len(asRunes) {
        length = len(asRunes) - start
    }
        
    return string(asRunes[start : start+length])
}

这段代码实现了一个函数substr,它接受一个字符串input、一个起始位置start和一个长度length作为参数,并返回从指定位置开始指定长度的子字符串。它首先将输入字符串转换为rune类型的切片,然后根据起始位置和长度进行截取操作。如果起始位置超过了字符串长度,则返回空字符串。如果起始位置加上长度超过了字符串长度,则将长度调整为剩余部分的长度。最后,将截取的子字符串转换为普通的字符串类型并返回。

英文:

Here's a length-based implementation based on the rune trick:

func substr(input string, start int, length int) string {
	asRunes := []rune(input)
	
	if start &gt;= len(asRunes) {
		return &quot;&quot;
	}
	
	if start+length &gt; len(asRunes) {
		length = len(asRunes) - start
	}
		
	return string(asRunes[start : start+length])
}

答案4

得分: 2

如果您不介意使用实验性的包,您可以使用以下代码:

package main
import "golang.org/x/exp/utf8string"

func main() {
   a := utf8string.NewString("ÄÅàâäåçèéêëìîïü")
   s := a.Slice(1, 3)
   println(s == "Åà")
}

您可以在https://pkg.go.dev/golang.org/x/exp/utf8string找到更多信息。

英文:

If you don't mind experimental package, you can use this:

package main
import &quot;golang.org/x/exp/utf8string&quot;

func main() {
   a := utf8string.NewString(&quot;&#196;&#197;&#224;&#226;&#228;&#229;&#231;&#232;&#233;&#234;&#235;&#236;&#238;&#239;&#252;&quot;)
   s := a.Slice(1, 3)
   println(s == &quot;&#197;&#224;&quot;)
}

https://pkg.go.dev/golang.org/x/exp/utf8string

huangapple
  • 本文由 发表于 2015年2月25日 20:08:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/28718682.html
匿名

发表评论

匿名网友

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

确定