How to split a string and assign it to variables

前端 未结 9 1532
无人及你
无人及你 2020-12-07 10:27

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

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

but in Go it does not see

相关标签:
9条回答
  • 2020-12-07 11:07
    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

    // 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) }
    
    0 讨论(0)
  • 2020-12-07 11:08

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

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        fmt.Printf("%q\n", strings.SplitAfter("z,o,r,r,o", ","))
    }
    
    0 讨论(0)
  • 2020-12-07 11:10

    There's are multiple ways to split a string :

    1. If you want to make it temporary then split like this:

    _

    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

    _

    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.Host and ServerDetail.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.Host and ServerDetail.Port.

    That's All.

    0 讨论(0)
  • 2020-12-07 11:11

    The IPv6 addresses for fields like RemoteAddr from http.Request are formatted as "[::1]:53343"

    So net.SplitHostPort works great:

    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>
    
    0 讨论(0)
  • 2020-12-07 11:14
    **In this function you can able to split the function by golang using array of strings**
    
    func SplitCmdArguments(args []string) map[string]string {
        m := make(map[string]string)
        for _, v := range args {
            strs := strings.Split(v, "=")
            if len(strs) == 2 {
                m[strs[0]] = strs[1]
            } else {
                log.Println("not proper arguments", strs)
            }
        }
        return m
    }
    
    0 讨论(0)
  • 2020-12-07 11:17

    Since go is flexible an you can create your own python style split ...

    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
    }
    
    0 讨论(0)
提交回复
热议问题