strings.SplitN() Function()是Go語言中的字符串操作函數。它用於將給定的字符串拆分為由分隔符分隔的子字符串。此函數返回這些分隔符之間所有子字符串的片段。
用法:
func SplitN(s, sep string, n int) []string
在這裏,s是字符串,sep是分隔符。如果s不包含給定的sep且sep為非空,則它將返回長度為1的切片,其中僅包含s。或者,如果sep為空,則它將在每個UTF-8序列之後拆分。或者,如果s和sep均為空,則它將返回一個空切片。
在這裏,最後一個參數確定函數要返回的字符串數。可以是以下任何一種:
- n等於零(n == 0):結果為nil,即零個子字符串。返回一個空列表。
- n大於零(n> 0):最多返回n個子字符串,最後一個字符串為未分割的餘數。
- n小於零(n <0):將返回所有可能的子字符串。
範例1:
// Golang program to illustrate the
// strings.SplitN() Function
package main
import (
"fmt"
"strings"
)
func main() {
// String s a is comma serparated string
// The separater used is ","
// This will split the string into 6 parts
s:= strings.SplitN("a,b,c,d,e,f", ",",6)
fmt.Println(s)
}
輸出:
[a b c d e f]
範例2:
// Golang program to illustrate the
// strings.SplitN() Function
package main
import (
"fmt"
"strings"
)
func main() {
// String s will be separated by spaces
// -1 implies all the possible sub strings
// that can be generated
s:= strings.SplitN("I love GeeksforGeeks portal!", " ", -1)
// This will print all the sub strings
// of string s in a new line
for _, v:= range s {
fmt.Println(v)
}
}
輸出:
I love GeeksforGeeks portal!
範例3:
// Golang program to illustrate the
// strings.SplitN() Function
package main
import (
"fmt"
"strings"
)
func main() {
// This will give empty sub string
// as 0 is provided as the last parameter
s:= strings.SplitN("a,b,c", ",", 0)
fmt.Println(s)
// This will give only 3 sub strings
// a and b will be the first 2 sub strings
s = strings.SplitN("a:b:c:d:e:f", ":", 3)
fmt.Println(s)
// Delimiter can be anything
// a -ve number specifies all sub strings
s = strings.SplitN("1234x5678x1234x5678", "x", -1)
fmt.Println(s)
// When the separator is not present in
// given list, original string is returned
s = strings.SplitN("qwerty", ",", 6)
fmt.Println(s)
}
輸出:
[] [a b c:d:e:f] [1234 5678 1234 5678] [qwerty]
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自vanigupta20024大神的英文原創作品 strings.SplitN() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。