在Go中对字符串进行分割。

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

Partition a string in Go

问题

如何从字符串中获取分隔符之前和之后的片段?在Python中,我可以简单地编写以下代码:

user, _, domain = "foo@example.com".partition("@")
assert user == "foo"
assert domain == "example.com"

值得注意的是,如果输入中存在多个分隔符或者没有分隔符,这种方法也能正常工作。那么在Go语言中,我该如何轻松地拆分字符串呢?

英文:

How do I get the slices before and after a separator from a string? In Python, I can simply write

user, _, domain = "foo@example.com".partition("@")
assert user == "foo"
assert domain == "example.com"

Notably, this also works if multiple occurrences of the separator are present in the input, or none at all. How can I split a string that easily in Go?

答案1

得分: 6

你可以使用这个辅助函数来包装 SplitN

import "strings"

func Partition(s string, sep string) (string, string, string) {
    parts := strings.SplitN(s, sep, 2)
    if len(parts) == 1 {
        return parts[0], "", ""
    }
    return parts[0], sep, parts[1]
}

这个函数将字符串 s 按照分隔符 sep 进行分割,并返回分割后的三个部分。如果分割后只有一个部分,则返回该部分和两个空字符串。

英文:

You can use this helper function which wraps SplitN:

import "strings"

func Partition(s string, sep string) (string, string, string) {
	parts := strings.SplitN(s, sep, 2)
	if len(parts) == 1 {
		return parts[0], "", ""
	}
	return parts[0], sep, parts[1]
}

答案2

得分: 4

从go 1.18开始,你可以使用strings.Cut函数。

func Cut(s, sep string) (before, after string, found bool)

Cut函数将字符串s在第一个sep实例周围切割,返回sep之前和之后的文本。found结果报告sep是否出现在s中。如果sep不在s中,则Cut函数返回s, "", false。

示例:

strings.Cut("Gopher", "Go") // 返回 "", "pher", true
strings.Cut("Gopher", "ph") // 返回 "Go", "er", true
strings.Cut("Gopher", "er") // 返回 "Goph", "", true
strings.Cut("Gopher", "Badger") // 返回 "Gopher", "", false
英文:

Starting with go 1.18, you can use strings.Cut

> func Cut(s, sep string) (before, after string, found bool)
>
> Cut slices s around the first instance of sep, returning the text before and after sep. The found result reports whether sep appears in s. If sep does not appear in s, cut returns s, "", false.

Examples:

strings.Cut("Gopher", "Go") // returns "", "pher", true
strings.Cut("Gopher", "ph") // returns "Go", "er", true
strings.Cut("Gopher", "er") // returns "Goph", "", true
strings.Cut("Gopher", "Badger") // returns "Gopher", "", false

答案3

得分: 1

确实,SplitN允许您解析最多n个字符串。如果您需要更简单的电子邮件检查方法,可以尝试下面的代码。不要忘记检查错误。

package main

import (
	"fmt"
	"strings"
	"errors"
)

func Separate(str, separator string) (string, string, error){
	sepIndex := strings.Index(str, separator)
	if sepIndex >= 0 {
		return str[0 : (sepIndex)], str[sepIndex+len(separator) : len(str)], nil
	} else {
		return "", "", errors.New("Separator not found!")
	}
}

func main(){
	str := "@xmyname@xample.com"

	fmt.Println("Initial string: ", str)

	p1, p2, err := Separate(str, "@x")
	if err != nil{
		fmt.Println(err)
	} else {
		fmt.Println("Slice 1:", p1, "\nSlice 2:",p2)
	}
}
英文:

Indeed SplitN allows you to parse at most n strings. If you need something simpler for e-mail check, you can try something like the code below. Don't forget to check the error.

package main

import (
	"fmt"
	"strings"
	"errors"
)

func Separate(str, separator string) (string, string, error){
	sepIndex := strings.Index(str, separator)
	if sepIndex >= 0 {
		return str[0 : (sepIndex)], str[sepIndex+len(separator) : len(str)], nil
	} else {
		return "", "", errors.New("Separator now found!")
	}
}

func main(){
	str := "@xmyname@xample.com"

	fmt.Println("Initial string: ", str)

	p1, p2, err := Separate(str, "@x")
	if err != nil{
		fmt.Println(err)
	} else {
		fmt.Println("Slice 1:", p1, "\nSlice 2:",p2)
	}
}

huangapple
  • 本文由 发表于 2013年10月30日 21:29:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/19683612.html
匿名

发表评论

匿名网友

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

确定