如何拆分字符串并将其赋值给变量

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

How to split a string and assign it to variables

问题

在Python中,可以将一个字符串拆分并赋值给变量:

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

但在Go语言中似乎无法这样做:

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

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

英文:

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 seem to work:

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?

答案1

得分: 274

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)
}

输出:

127.0.0.1 5432

package main

import (
"fmt"
"net"
)

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

输出:

127.0.0.1 5432

英文:

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>

答案2

得分: 21

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
}

英文:

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

package main

import (
	&quot;fmt&quot;
	&quot;strings&quot;
	&quot;errors&quot;
)

type PyString string

func main() {
	var py PyString
	py = &quot;127.0.0.1:5432&quot;
	ip, port , err := py.Split(&quot;:&quot;)       // 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) &lt; 2 {
		return &quot;&quot; , &quot;&quot;, errors.New(&quot;Minimum match not found&quot;)
	}
	return s[0] , s[1] , nil
}

答案3

得分: 9

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>
英文:

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

So net.SplitHostPort works great:

package main

    import (
        &quot;fmt&quot;
        &quot;net&quot;
    )

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

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

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

Output is:

127.0.0.1 5432 &lt;nil&gt;
::1 2345 &lt;nil&gt;
localhost 1234 &lt;nil&gt;

答案4

得分: 3

Golang不支持隐式解包切片(不像Python),这就是为什么这样不起作用的原因。就像上面给出的例子一样,我们需要绕过它。

另外一点:

在Go中,可变参数函数会发生隐式解包:

func varParamFunc(params ...int) {

}

varParamFunc(slice1...)
英文:

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.

One side note:

The implicit unpacking happens for variadic functions in go:

func varParamFunc(params ...int) {

}

varParamFunc(slice1...)

答案5

得分: 2

这是strings.Split的定义:

// Split将s切割成由sep分隔的所有子字符串,并返回这些分隔符之间的子字符串的切片。
//
// 如果s不包含sep并且sep不为空,则Split返回一个长度为1的切片,其唯一元素为s。
//
// 如果sep为空,则Split在每个UTF-8序列之后进行切割。如果s和sep都为空,则Split返回一个空切片。
//
// 它等同于SplitN,其计数为-1。
func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }

英文:
package main

import (
    &quot;fmt&quot;
    &quot;strings&quot;
)

func main() {
    strs := strings.Split(&quot;127.0.0.1:5432&quot;, &quot;:&quot;)
    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) }

答案6

得分: 1

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

  1. 如果你想要临时拆分字符串,可以这样拆分:

_

import net package

host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//在这里编写你的代码
}
fmt.Println(host, port)
  1. 基于结构体拆分:
  • 创建一个结构体并进行拆分

_

type ServerDetail struct {
    Host       string
    Port       string
    err        error
}

ServerDetail = net.SplitHostPort("0.0.0.1:8080") //针对Host和Port

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

如果你不想拆分特定的字符串,可以这样做:

type ServerDetail struct {
    Host       string
    Port       string
}

ServerDetail = strings.Split([Your_String], ":") //常用的拆分方法

然后像这样使用ServerDetail.HostServerDetail.Port

就是这样。

英文:

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(&quot;0.0.0.1:8080&quot;)
if err != nil {
fmt.Println(&quot;Error is splitting : &quot;+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(&quot;0.0.0.1:8080&quot;) //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], &quot;:&quot;) // Common split method

and use like ServerDetail.Host and ServerDetail.Port.

That's All.

答案7

得分: 1

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

示例:

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

英文:

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.

example :

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

答案8

得分: 1

作为一个附注,你可以在Go语言中在分割字符串时包含分隔符。要这样做,可以使用strings.SplitAfter,如下面的示例所示。

package main

import (
	"fmt"
	"strings"
)

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

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 (
	&quot;fmt&quot;
	&quot;strings&quot;
)

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

答案9

得分: 1

在这个函数中,你可以使用字符串数组将函数拆分为golang。

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
}
英文:
**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, &quot;=&quot;)
		if len(strs) == 2 {
			m[strs[0]] = strs[1]
		} else {
			log.Println(&quot;not proper arguments&quot;, strs)
		}
	}
	return m
}


</details>



huangapple
  • 本文由 发表于 2013年5月15日 03:31:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/16551354.html
匿名

发表评论

匿名网友

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

确定