Golfing常用パッケージ-strings.go

23877 ワード

strings.go
// Count       sep   s        
//    sep      ,    s     (   )   + 1
//    Rabin-Karp     
func Count(s, sep string) int

func main() {
    s := "Hello,  !!!!!"
    n := strings.Count(s, "!")
    fmt.Println(n) // 5
    n = strings.Count(s, "!!")
    fmt.Println(n) // 2
}

------------------------------------------------------------

// Contains       s         substr
//    substr   ,    true
func Contains(s, substr string) bool

func main() {
    s := "Hello,  !!!!!"
    b := strings.Contains(s, "!!")
    fmt.Println(b) // true
    b = strings.Contains(s, "!?")
    fmt.Println(b) // false
    b = strings.Contains(s, "")
    fmt.Println(b) // true
}

------------------------------------------------------------

// ContainsAny       s       chars         
//    chars   ,    false
func ContainsAny(s, chars string) bool

func main() {
    s := "Hello,  !"
    b := strings.ContainsAny(s, "abc")
    fmt.Println(b) // false
    b = strings.ContainsAny(s, "def")
    fmt.Println(b) // true
    b = strings.Contains(s, "")
    fmt.Println(b) // true
}

------------------------------------------------------------

// ContainsRune       s         r
func ContainsRune(s string, r rune) bool

func main() {
    s := "Hello,  !"
    b := strings.ContainsRune(s, '
') fmt.Println(b) // false b = strings.ContainsRune(s, ' ') fmt.Println(b) // true b = strings.ContainsRune(s, 0) fmt.Println(b) // false } ------------------------------------------------------------ // Index sep s // , -1, sep , 0。 // Rabin-Karp func Index(s, sep string) int func main() { s := "Hello, !" i := strings.Index(s, "h") fmt.Println(i) // -1 i = strings.Index(s, "!") fmt.Println(i) // 12 i = strings.Index(s, "") fmt.Println(i) // 0 } ------------------------------------------------------------ // LastIndex sep s // , -1, sep , // func LastIndex(s, sep string) int func main() { s := "Hello, ! Hello!" i := strings.LastIndex(s, "h") fmt.Println(i) // -1 i = strings.LastIndex(s, "H") fmt.Println(i) // 14 i = strings.LastIndex(s, "") fmt.Println(i) // 20 } ------------------------------------------------------------ // IndexRune r s // , -1 func IndexRune(s string, r rune) int func main() { s := "Hello, ! Hello!" i := strings.IndexRune(s, '
') fmt.Println(i) // -1 i = strings.IndexRune(s, ' ') fmt.Println(i) // 9 i = strings.IndexRune(s, 0) fmt.Println(i) // -1 } ------------------------------------------------------------ // IndexAny chars s // , -1, chars , -1 func IndexAny(s, chars string) int func main() { s := "Hello, ! Hello!" i := strings.IndexAny(s, "abc") fmt.Println(i) // -1 i = strings.IndexAny(s, "def") fmt.Println(i) // 1 i = strings.IndexAny(s, "") fmt.Println(i) // -1 } ------------------------------------------------------------ // LastIndexAny chars s // , -1, chars , -1 func LastIndexAny(s, chars string) int func main() { s := "Hello, ! Hello!" i := strings.LastIndexAny(s, "abc") fmt.Println(i) // -1 i = strings.LastIndexAny(s, "def") fmt.Println(i) // 15 i = strings.LastIndexAny(s, "") fmt.Println(i) // -1 } ------------------------------------------------------------ // SplitN sep , s , sep // sep , s Unicode 。 // s sep , s []string // n , 。 // n 0, nil, n 0, , func SplitN(s, sep string, n int) []string func main() { s := "Hello, ! Hello!" ss := strings.SplitN(s, " ", 2) fmt.Printf("%q
", ss) // ["Hello," " ! Hello!"] ss = strings.SplitN(s, " ", -1) fmt.Printf("%q
", ss) // ["Hello," " !" "Hello!"] ss = strings.SplitN(s, "", 3) fmt.Printf("%q
", ss) // ["H" "e" "llo, ! Hello!"] } ------------------------------------------------------------ // SplitN sep , s , sep // sep , s Unicode 。 // s sep , s []string // n , 。 // n 0, nil, n 0, , func SplitAfterN(s, sep string, n int) []string func main() { s := "Hello, ! Hello!" ss := strings.SplitAfterN(s, " ", 2) fmt.Printf("%q
", ss) // ["Hello, " " ! Hello!"] ss = strings.SplitAfterN(s, " ", -1) fmt.Printf("%q
", ss) // ["Hello, " " ! " "Hello!"] ss = strings.SplitAfterN(s, "", 3) fmt.Printf("%q
", ss) // ["H" "e" "llo, ! Hello!"] } ------------------------------------------------------------ // Split sep , s , sep // sep , s Unicode 。 // s sep , s []string func Split(s, sep string) []string func main() { s := "Hello, ! Hello!" ss := strings.Split(s, " ") fmt.Printf("%q
", ss) // ["Hello," " !" "Hello!"] ss = strings.Split(s, ", ") fmt.Printf("%q
", ss) // ["Hello" " ! Hello!"] ss = strings.Split(s, "") fmt.Printf("%q
", ss) // } ------------------------------------------------------------ // SplitAfter sep , s , sep // sep , s Unicode 。 // s sep , s []string func SplitAfter(s, sep string) []string func main() { s := "Hello, ! Hello!" ss := strings.SplitAfter(s, " ") fmt.Printf("%q
", ss) // ["Hello, " " ! " "Hello!"] ss = strings.SplitAfter(s, ", ") fmt.Printf("%q
", ss) // ["Hello, " " ! Hello!"] ss = strings.SplitAfter(s, "") fmt.Printf("%q
", ss) // } ------------------------------------------------------------ // Fields , s , // :\t,
, \v, \f, \r, ' ', U+0085 (NEL), U+00A0 (NBSP) // s , func Fields(s string) []string func main() { s := "Hello, ! Hello!" ss := strings.Fields(s) fmt.Printf("%q
", ss) // ["Hello," " !" "Hello!"] } ------------------------------------------------------------ // FieldsFunc f(rune) , // s , 。 // s f(rune) , 。 func FieldsFunc(s string, f func(rune) bool) []string func isSlash(r rune) bool { return r == '\\' || r == '/' } func main() { s := "C:\\Windows\\System32\\FileName" ss := strings.FieldsFunc(s, isSlash) fmt.Printf("%q
", ss) // ["C:" "Windows" "System32" "FileName"] } ------------------------------------------------------------ // Join a , sep func Join(a []string, sep string) string func main() { ss := []string{"Monday", "Tuesday", "Wednesday"} s := strings.Join(ss, "|") fmt.Printf("%q
", s) // "Monday|Tuesday|Wednesday" } ------------------------------------------------------------ // HasPrefix s prefix func HasPrefix(s, prefix string) bool func main() { s := "Hello !" b := strings.HasPrefix(s, "hello") fmt.Println(b) // false b = strings.HasPrefix(s, "Hello") fmt.Println(b) // true } ------------------------------------------------------------ // HasPrefix s prefix func HasSuffix(s, suffix string) bool func main() { s := "Hello !" b := strings.HasSuffix(s, " ") fmt.Println(b) // false b = strings.HasSuffix(s, " !") fmt.Println(b) // true } ------------------------------------------------------------ // Map s mapping(rune) mapping(rune) 。 // mapping(rune) , 。 func Map(mapping func(rune) rune, s string) string func Slash(r rune) rune { if r == '\\' { return '/' } return r } func main() { s := "C:\\Windows\\System32\\FileName" ms := strings.Map(Slash, s) fmt.Printf("%q
", ms) // "C:/Windows/System32/FileName" } ------------------------------------------------------------ // Repeat count s func Repeat(s string, count int) string func main() { s := "Hello!" rs := strings.Repeat(s, 3) fmt.Printf("%q
", rs) // "Hello!Hello!Hello!" } ------------------------------------------------------------ // ToUpper s // ASCII , func ToUpper(s string) string // ToLower s // ASCII , func ToLower(s string) string // ToTitle s Title // Title Upper // Title // ToTitle Title func ToTitle(s string) string func main() { s := "heLLo worLd Abc" us := strings.ToUpper(s) ls := strings.ToLower(s) ts := strings.ToTitle(s) fmt.Printf("%q
", us) // "HELLO WORLD ABC" fmt.Printf("%q
", ls) // "hello world abc" fmt.Printf("%q
", ts) // "HELLO WORLD ABC" } // ASCII Title func main() { for _, cr := range unicode.CaseRanges { // u := uint32(cr.Delta[unicode.UpperCase]) // // l := uint32(cr.Delta[unicode.LowerCase]) // t := uint32(cr.Delta[unicode.TitleCase]) // Title // if t != 0 && t != u { if t != 0 { for i := cr.Lo; i <= cr.Hi; i++ { fmt.Printf("%c -> %c
", i, i+t) } } } } ------------------------------------------------------------ // ToUpperSpecial s 。 // _case func ToUpperSpecial(_case unicode.SpecialCase, s string) string // ToLowerSpecial s 。 // _case func ToLowerSpecial(_case unicode.SpecialCase, s string) string // ToTitleSpecial s Title 。 // _case func ToTitleSpecial(_case unicode.SpecialCase, s string) string _case , : unicode.CaseRange{'A', 'Z', [unicode.MaxCase]rune{3, -3, 0}} · 'A', 'Z' 'A' 'Z' 。 · [unicode.MaxCase]rune : ToUpperSpecial , Unicode (3) ToLowerSpecial , Unicode (-3) ToTitleSpecial , Unicode (0) func main() { // var _MyCase = unicode.SpecialCase{ // ,ToTitle unicode.CaseRange{',', ',', [unicode.MaxCase]rune{',' - ',', ',' - ',', 0}}, // ,ToTitle unicode.CaseRange{'.', '.', [unicode.MaxCase]rune{'。' - '.', '。' - '.', 0}}, // ABC ABC、abc,ToTitle unicode.CaseRange{'A', 'C', [unicode.MaxCase]rune{'A' - 'A', 'a' - 'A', 0}}, } s := "ABCDEF,abcdef." us := strings.ToUpperSpecial(_MyCase, s) fmt.Printf("%q
", us) // "ABCDEF,ABCDEF。" ls := strings.ToLowerSpecial(_MyCase, s) fmt.Printf("%q
", ls) // "abcdef,abcdef。" ts := strings.ToTitleSpecial(_MyCase, s) fmt.Printf("%q
", ts) // "ABCDEF,ABCDEF." } ------------------------------------------------------------ // Title s Title // BUG: Title Unicode func Title(s string) string func main() { s := "heLLo worLd" ts := strings.Title(s) fmt.Printf("%q
", ts) // "HeLLo WorLd" } ------------------------------------------------------------ // TrimLeftFunc s f(rune) func TrimLeftFunc(s string, f func(rune) bool) string func isSlash(r rune) bool { return r == '\\' || r == '/' } func main() { s := "\\\\HostName\\C\\Windows\\" ts := strings.TrimLeftFunc(s, isSlash) fmt.Printf("%q
", ts) // "HostName\\C\\Windows\\" } ------------------------------------------------------------ // TrimRightFunc s f(rune) func TrimRightFunc(s string, f func(rune) bool) string func isSlash(r rune) bool { return r == '\\' || r == '/' } func main() { s := "\\\\HostName\\C\\Windows\\" ts := strings.TrimRightFunc(s, isSlash) fmt.Printf("%q
", ts) // "\\\\HostName\\C\\Windows" } ------------------------------------------------------------ // TrimFunc s f(rune) func TrimFunc(s string, f func(rune) bool) string func isSlash(r rune) bool { return r == '\\' || r == '/' } func main() { s := "\\\\HostName\\C\\Windows\\" ts := strings.TrimFunc(s, isSlash) fmt.Printf("%q
", ts) // "HostName\\C\\Windows" } ------------------------------------------------------------ // s f(rune) 。 // f(rune) , -1 func IndexFunc(s string, f func(rune) bool) int func isSlash(r rune) bool { return r == '\\' || r == '/' } func main() { s := "C:\\Windows\\System32" i := strings.IndexFunc(s, isSlash) fmt.Printf("%v
", i) // 2 } ------------------------------------------------------------ // s f(rune) 。 // f(rune) , -1 func LastIndexFunc(s string, f func(rune) bool) int func isSlash(r rune) bool { return r == '\\' || r == '/' } func main() { s := "C:\\Windows\\System32" i := strings.LastIndexFunc(s, isSlash) fmt.Printf("%v
", i) // 10 } ------------------------------------------------------------ // Trim s cutset func Trim(s string, cutset string) string func main() { s := " Hello ! " ts := strings.Trim(s, " Helo!") fmt.Printf("%q
", ts) // " " } ------------------------------------------------------------ // TrimLeft s cutset func TrimLeft(s string, cutset string) string func main() { s := " Hello ! " ts := strings.TrimLeft(s, " Helo") fmt.Printf("%q
", ts) // " ! " } ------------------------------------------------------------ // TrimRight s cutset func TrimRight(s string, cutset string) string func main() { s := " Hello ! " ts := strings.TrimRight(s, " !") fmt.Printf("%q
", ts) // " Hello" } ------------------------------------------------------------ // TrimSpace s func TrimSpace(s string) string func main() { s := " Hello ! " ts := strings.TrimSpace(s) fmt.Printf("%q
", ts) // "Hello !" } ------------------------------------------------------------ // TrimPrefix s prefix // s prefix , s func TrimPrefix(s, prefix string) string func main() { s := "Hello !" ts := strings.TrimPrefix(s, "Hello") fmt.Printf("%q
", ts) // " " } ------------------------------------------------------------ // TrimSuffix s suffix // s suffix , s func TrimSuffix(s, suffix string) string func main() { s := "Hello !!!!!" ts := strings.TrimSuffix(s, "!!!!") fmt.Printf("%q
", ts) // " " } ------------------------------------------------------------ // Replace s , old new // n , n -1, // old , new func Replace(s, old, new string, n int) string func main() { s := "Hello !" s = strings.Replace(s, " ", ",", -1) fmt.Println(s) s = strings.Replace(s, "", "|", -1) fmt.Println(s) } ------------------------------------------------------------ // EqualFold s t 。 , // “ϕ” “Φ”、 “DŽ” “Dž” , func EqualFold(s, t string) bool func main() { s1 := "Hello ! ϕ DŽ" s2 := "hello ! Φ Dž" b := strings.EqualFold(s1, s2) fmt.Printf("%v
", b) // true } ============================================================ // reader.go ------------------------------------------------------------ // Reader , io.Reader,io.ReaderAt, // io.Seeker,io.WriterTo,io.ByteScanner,io.RuneScanner type Reader struct { s string // i int // , i prevRune int // , 0 } // s strings.Reader // bytes.NewBufferString // bytes.NewBufferString , func NewReader(s string) *Reader { return &Reader{s, 0, -1} } ------------------------------------------------------------ // Len r.i func (r *Reader) Len() int func main() { s := "Hello !" // Reader r := strings.NewReader(s) // fmt.Println(r.Len()) // 13 } ------------------------------------------------------------ // Read r.i b ( b ) // // , io.EOF func (r *Reader) Read(b []byte) (n int, err error) func main() { s := "Hello World!" // Reader r := strings.NewReader(s) // 5 b := make([]byte, 5) // r for n, _ := r.Read(b); n > 0; n, _ = r.Read(b) { fmt.Printf("%q, ", b[:n]) // "Hello", " Worl", "d!" } } ------------------------------------------------------------ // ReadAt off b ( b ) // // , io.EOF // , io.EOF func (r *Reader) ReadAt(b []byte, off int64) (n int, err error) func main() { s := "Hello World!" // Reader r := strings.NewReader(s) // 5 b := make([]byte, 5) // r n, _ := r.ReadAt(b, 0) fmt.Printf("%q
", b[:n]) // "Hello" // r n, _ = r.ReadAt(b, 6) fmt.Printf("%q
", b[:n]) // "World" } ------------------------------------------------------------ // ReadByte r.i b // // , io.EOF func (r *Reader) ReadByte() (b byte, err error) func main() { s := "Hello World!" // Reader r := strings.NewReader(s) // r for i := 0; i < 3; i++ { b, _ := r.ReadByte() fmt.Printf("%q, ", b) // 'H', 'e', 'l', } } ------------------------------------------------------------ // UnreadByte ReadByte , r.i-- func (r *Reader) UnreadByte() error func main() { s := "Hello World!" // Reader r := strings.NewReader(s) // r for i := 0; i < 3; i++ { b, _ := r.ReadByte() fmt.Printf("%q, ", b) // 'H', 'H', 'H', r.UnreadByte() // } } ------------------------------------------------------------ // ReadRune r.i ch // ch: // size:ch // err: // , io.EOF // r.i UTF-8 , utf8.RuneError func (r *Reader) ReadRune() (ch rune, size int, err error) func main() { s := " !" // Reader r := strings.NewReader(s) // r for i := 0; i < 5; i++ { b, n, _ := r.ReadRune() fmt.Printf(`"%c:%v", `, b, n) // " :3", " :3", " :1", " :3", " :3", } } ------------------------------------------------------------ // ReadRune func (r *Reader) UnreadRune() error func main() { s := " !" // Reader r := strings.NewReader(s) // r for i := 0; i < 5; i++ { b, _, _ := r.ReadRune() fmt.Printf("%q, ", b) // ' ', ' ', ' ', ' ', ' ', r.UnreadRune() // } } ------------------------------------------------------------ // Seek r // offset: , // whence: ,0: ,1: ,2: // whence 0、1、2, // , // 1 << 31, func (r *Reader) Seek(offset int64, whence int) (int64, error) func main() { s := "Hello World!" // Reader r := strings.NewReader(s) // b := make([]byte, 5) // r r.Seek(6, 0) // 7 r.Read(b) // fmt.Printf("%q
", b) r.Seek(-5, 1) // r.Read(b) // fmt.Printf("%q
", b) } ------------------------------------------------------------ // WriteTo r.i w func (r *Reader) WriteTo(w io.Writer) (n int64, err error) func main() { s := "Hello World!" // Reader r := strings.NewReader(s) // bytes.Buffer , io.Reader buf := bytes.NewBuffer(nil) // r buf r.WriteTo(buf) fmt.Printf("%q
", buf) // "Hello World!" } ============================================================ // replace.go ------------------------------------------------------------ // Replacer type Replacer struct { Replace(s string) string WriteString(w io.Writer, s string) (n int, err error) } ------------------------------------------------------------ // NewReplacer “ ” Replacer 。 // “ ” , 。 // , 。 // “ ” “ ”, “ ” func NewReplacer(oldnew ...string) *Replacer ------------------------------------------------------------ // Replace s “ ” // Replace Boyer-Moore , func (r *Replacer) Replace(s string) string func main() { srp := strings.NewReplacer("Hello", " ", "World", " ", "!", "!") s := "Hello World!Hello World!hello world!" rst := srp.Replace(s) fmt.Print(rst) // ! !hello world! } func main() { wl := []string{"Hello", "Hi", "Hello", " "} srp := strings.NewReplacer(wl...) s := "Hello World! Hello World! hello world!" rst := srp.Replace(s) fmt.Print(rst) // Hi World! Hi World! hello world! } ------------------------------------------------------------ // WriteString s “ ”, w func (r *Replacer) WriteString(w io.Writer, s string) (n int, err error) func main() { wl := []string{"Hello", " ", "World", " ", "!", "!"} srp := strings.NewReplacer(wl...) s := "Hello World!Hello World!hello world!" srp.WriteString(os.Stdout, s) // ! !hello world! }