string 如何拆分字符串并将其分配给变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16551354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:55:58  来源:igfitidea点击:

How to split a string and assign it to variables

stringgosplit

提问by Pyt

In Python it is possible to split a string and assign it to variables:

在 Python 中,可以拆分字符串并将其分配给变量:

ip, port = '127.0.0.1:5432'.split(':')

but in Go it does not seem to work:

但在 Go 中它似乎不起作用:

ip, port := strings.Split("127.0.0.1:5432", ":")
// assignment count mismatch: 2 = 1

Question:How to split a string and assign values in one step?

问题:如何一步拆分字符串并赋值?

回答by peterSO

Two steps, for example,

两个步骤,例如,

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := strings.Split("127.0.0.1:5432", ":")
    ip, port := s[0], s[1]
    fmt.Println(ip, port)
}

Output:

输出:

127.0.0.1 5432

One step, for example,

一个步骤,例如,

package main

import (
    "fmt"
    "net"
)

func main() {
    host, port, err := net.SplitHostPort("127.0.0.1:5432")
    fmt.Println(host, port, err)
}

Output:

输出:

127.0.0.1 5432 <nil>

回答by Baba

Since gois flexible an you can create your own pythonstyle split ...

由于go灵活,您可以创建自己的python样式拆分...

package main

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

type PyString string

func main() {
    var py PyString
    py = "127.0.0.1:5432"
    ip, port , err := py.Split(":")       // Python Style
    fmt.Println(ip, port, err)
}

func (py PyString) Split(str string) ( string, string , error ) {
    s := strings.Split(string(py), str)
    if len(s) < 2 {
        return "" , "", errors.New("Minimum match not found")
    }
    return s[0] , s[1] , nil
}

回答by Glenn McElhoe

The IPv6 addresses for fields like RemoteAddrfrom http.Requestare formatted as "[::1]:53343"

RemoteAddrfromhttp.Request等字段的 IPv6 地址格式为“[::1]:53343”

So net.SplitHostPortworks great:

所以net.SplitHostPort效果很好:

package main

    import (
        "fmt"
        "net"
    )

    func main() {
        host1, port, err := net.SplitHostPort("127.0.0.1:5432")
        fmt.Println(host1, port, err)

        host2, port, err := net.SplitHostPort("[::1]:2345")
        fmt.Println(host2, port, err)

        host3, port, err := net.SplitHostPort("localhost:1234")
        fmt.Println(host3, port, err)
    }

Output is:

输出是:

127.0.0.1 5432 <nil>
::1 2345 <nil>
localhost 1234 <nil>

回答by monkrus

As a side note, you can include the separators while splitting the string in Go. To do so, use strings.SplitAfteras in the example below.

作为旁注,您可以在 Go 中拆分字符串时包含分隔符。为此,请使用strings.SplitAfter以下示例。

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Printf("%q\n", strings.SplitAfter("z,o,r,r,o", ","))
}

回答by Prabesh P

package main

import (
    "fmt"
    "strings"
)

func main() {
    strs := strings.Split("127.0.0.1:5432", ":")
    ip := strs[0]
    port := strs[1]
    fmt.Println(ip, port)
}

Here is the definition for strings.Split

这是strings.Split的定义

// Split slices s into all substrings separated by sep and returns a slice of
// the substrings between those separators.
//
// If s does not contain sep and sep is not empty, Split returns a
// slice of length 1 whose only element is s.
//
// If sep is empty, Split splits after each UTF-8 sequence. If both s
// and sep are empty, Split returns an empty slice.
//
// It is equivalent to SplitN with a count of -1.
func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }

回答by Hardik Bohra

What you are doing is, you are accepting split response in two different variables, and strings.Split() is returning only one response and that is an array of string. you need to store it to single variable and then you can extract the part of string by fetching the index value of an array.

您正在做的是,您正在接受两个不同变量中的拆分响应,而 strings.Split() 仅返回一个响应,即一个字符串数组。您需要将其存储到单个变量中,然后您可以通过获取数组的索引值来提取字符串的一部分。

example :

例子 :

 var hostAndPort string
    hostAndPort = "127.0.0.1:8080"
    sArray := strings.Split(hostAndPort, ":")
    fmt.Println("host : " + sArray[0])
    fmt.Println("port : " + sArray[1])

回答by amku91

There's are multiple ways to split a string :

有多种方法可以拆分字符串:

  1. If you want to make it temporary then split like this:
  1. 如果你想让它成为临时的,那么像这样拆分:

_

_

import net package

host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)
  1. Split based on struct :

    • Create a struct and split like this
  1. 基于 struct 拆分:

    • 创建一个结构体并像这样拆分

_

_

type ServerDetail struct {
    Host       string
    Port       string
    err        error
}

ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port

Now use in you code like ServerDetail.Hostand ServerDetail.Port

现在在你的代码中使用ServerDetail.HostServerDetail.Port

If you don't want to split specific string do it like this:

如果您不想拆分特定字符串,请执行以下操作:

type ServerDetail struct {
    Host       string
    Port       string
}

ServerDetail = strings.Split([Your_String], ":") // Common split method

and use like ServerDetail.Hostand ServerDetail.Port.

并使用 likeServerDetail.HostServerDetail.Port

That's All.

就这样。

回答by pr-pal

Golang does not support implicit unpacking of an slice (unlike python) and that is the reason this would not work. Like the examples given above, we would need to workaround it.

Golang 不支持切片的隐式解包(与 python 不同),这就是它不起作用的原因。像上面给出的例子一样,我们需要解决它。

One side note:

一方面说明:

The implicit unpacking happens for variadic functions in go:

隐式解包发生在 go 中的可变参数函数中:

func varParamFunc(params ...int) {

}

varParamFunc(slice1...)