github.com/eun/go@v0.0.0-20170811110501-92cfd07a6cfd/src/strings/strings.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package strings implements simple functions to manipulate UTF-8 encoded strings. 6 // 7 // For information about UTF-8 strings in Go, see https://blog.golang.org/strings. 8 package strings 9 10 import ( 11 "unicode" 12 "unicode/utf8" 13 ) 14 15 // explode splits s into a slice of UTF-8 strings, 16 // one string per Unicode character up to a maximum of n (n < 0 means no limit). 17 // Invalid UTF-8 sequences become correct encodings of U+FFFD. 18 func explode(s string, n int) []string { 19 l := utf8.RuneCountInString(s) 20 if n < 0 || n > l { 21 n = l 22 } 23 a := make([]string, n) 24 for i := 0; i < n-1; i++ { 25 ch, size := utf8.DecodeRuneInString(s) 26 a[i] = s[:size] 27 s = s[size:] 28 if ch == utf8.RuneError { 29 a[i] = string(utf8.RuneError) 30 } 31 } 32 if n > 0 { 33 a[n-1] = s 34 } 35 return a 36 } 37 38 // primeRK is the prime base used in Rabin-Karp algorithm. 39 const primeRK = 16777619 40 41 // hashStr returns the hash and the appropriate multiplicative 42 // factor for use in Rabin-Karp algorithm. 43 func hashStr(sep string) (uint32, uint32) { 44 hash := uint32(0) 45 for i := 0; i < len(sep); i++ { 46 hash = hash*primeRK + uint32(sep[i]) 47 } 48 var pow, sq uint32 = 1, primeRK 49 for i := len(sep); i > 0; i >>= 1 { 50 if i&1 != 0 { 51 pow *= sq 52 } 53 sq *= sq 54 } 55 return hash, pow 56 } 57 58 // hashStrRev returns the hash of the reverse of sep and the 59 // appropriate multiplicative factor for use in Rabin-Karp algorithm. 60 func hashStrRev(sep string) (uint32, uint32) { 61 hash := uint32(0) 62 for i := len(sep) - 1; i >= 0; i-- { 63 hash = hash*primeRK + uint32(sep[i]) 64 } 65 var pow, sq uint32 = 1, primeRK 66 for i := len(sep); i > 0; i >>= 1 { 67 if i&1 != 0 { 68 pow *= sq 69 } 70 sq *= sq 71 } 72 return hash, pow 73 } 74 75 // countGeneric implements Count. 76 func countGeneric(s, substr string) int { 77 // special case 78 if len(substr) == 0 { 79 return utf8.RuneCountInString(s) + 1 80 } 81 n := 0 82 for { 83 i := Index(s, substr) 84 if i == -1 { 85 return n 86 } 87 n++ 88 s = s[i+len(substr):] 89 } 90 } 91 92 // Contains reports whether substr is within s. 93 func Contains(s, substr string) bool { 94 return Index(s, substr) >= 0 95 } 96 97 // ContainsAny reports whether any Unicode code points in chars are within s. 98 func ContainsAny(s, chars string) bool { 99 return IndexAny(s, chars) >= 0 100 } 101 102 // ContainsRune reports whether the Unicode code point r is within s. 103 func ContainsRune(s string, r rune) bool { 104 return IndexRune(s, r) >= 0 105 } 106 107 // LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s. 108 func LastIndex(s, substr string) int { 109 n := len(substr) 110 switch { 111 case n == 0: 112 return len(s) 113 case n == 1: 114 return LastIndexByte(s, substr[0]) 115 case n == len(s): 116 if substr == s { 117 return 0 118 } 119 return -1 120 case n > len(s): 121 return -1 122 } 123 // Rabin-Karp search from the end of the string 124 hashss, pow := hashStrRev(substr) 125 last := len(s) - n 126 var h uint32 127 for i := len(s) - 1; i >= last; i-- { 128 h = h*primeRK + uint32(s[i]) 129 } 130 if h == hashss && s[last:] == substr { 131 return last 132 } 133 for i := last - 1; i >= 0; i-- { 134 h *= primeRK 135 h += uint32(s[i]) 136 h -= pow * uint32(s[i+n]) 137 if h == hashss && s[i:i+n] == substr { 138 return i 139 } 140 } 141 return -1 142 } 143 144 // IndexRune returns the index of the first instance of the Unicode code point 145 // r, or -1 if rune is not present in s. 146 // If r is utf8.RuneError, it returns the first instance of any 147 // invalid UTF-8 byte sequence. 148 func IndexRune(s string, r rune) int { 149 switch { 150 case 0 <= r && r < utf8.RuneSelf: 151 return IndexByte(s, byte(r)) 152 case r == utf8.RuneError: 153 for i, r := range s { 154 if r == utf8.RuneError { 155 return i 156 } 157 } 158 return -1 159 case !utf8.ValidRune(r): 160 return -1 161 default: 162 return Index(s, string(r)) 163 } 164 } 165 166 // IndexAny returns the index of the first instance of any Unicode code point 167 // from chars in s, or -1 if no Unicode code point from chars is present in s. 168 func IndexAny(s, chars string) int { 169 if len(chars) > 0 { 170 if len(s) > 8 { 171 if as, isASCII := makeASCIISet(chars); isASCII { 172 for i := 0; i < len(s); i++ { 173 if as.contains(s[i]) { 174 return i 175 } 176 } 177 return -1 178 } 179 } 180 for i, c := range s { 181 for _, m := range chars { 182 if c == m { 183 return i 184 } 185 } 186 } 187 } 188 return -1 189 } 190 191 // LastIndexAny returns the index of the last instance of any Unicode code 192 // point from chars in s, or -1 if no Unicode code point from chars is 193 // present in s. 194 func LastIndexAny(s, chars string) int { 195 if len(chars) > 0 { 196 if len(s) > 8 { 197 if as, isASCII := makeASCIISet(chars); isASCII { 198 for i := len(s) - 1; i >= 0; i-- { 199 if as.contains(s[i]) { 200 return i 201 } 202 } 203 return -1 204 } 205 } 206 for i := len(s); i > 0; { 207 r, size := utf8.DecodeLastRuneInString(s[:i]) 208 i -= size 209 for _, c := range chars { 210 if r == c { 211 return i 212 } 213 } 214 } 215 } 216 return -1 217 } 218 219 // LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s. 220 func LastIndexByte(s string, c byte) int { 221 for i := len(s) - 1; i >= 0; i-- { 222 if s[i] == c { 223 return i 224 } 225 } 226 return -1 227 } 228 229 // Generic split: splits after each instance of sep, 230 // including sepSave bytes of sep in the subarrays. 231 func genSplit(s, sep string, sepSave, n int) []string { 232 if n == 0 { 233 return nil 234 } 235 if sep == "" { 236 return explode(s, n) 237 } 238 if n < 0 { 239 n = Count(s, sep) + 1 240 } 241 242 a := make([]string, n) 243 n-- 244 i := 0 245 for i < n { 246 m := Index(s, sep) 247 if m < 0 { 248 break 249 } 250 a[i] = s[:m+sepSave] 251 s = s[m+len(sep):] 252 i++ 253 } 254 a[i] = s 255 return a[:i+1] 256 } 257 258 // SplitN slices s into substrings separated by sep and returns a slice of 259 // the substrings between those separators. 260 // 261 // The count determines the number of substrings to return: 262 // n > 0: at most n substrings; the last substring will be the unsplit remainder. 263 // n == 0: the result is nil (zero substrings) 264 // n < 0: all substrings 265 // 266 // Edge cases for s and sep (for example, empty strings) are handled 267 // as described in the documentation for Split. 268 func SplitN(s, sep string, n int) []string { return genSplit(s, sep, 0, n) } 269 270 // SplitAfterN slices s into substrings after each instance of sep and 271 // returns a slice of those substrings. 272 // 273 // The count determines the number of substrings to return: 274 // n > 0: at most n substrings; the last substring will be the unsplit remainder. 275 // n == 0: the result is nil (zero substrings) 276 // n < 0: all substrings 277 // 278 // Edge cases for s and sep (for example, empty strings) are handled 279 // as described in the documentation for SplitAfter. 280 func SplitAfterN(s, sep string, n int) []string { 281 return genSplit(s, sep, len(sep), n) 282 } 283 284 // Split slices s into all substrings separated by sep and returns a slice of 285 // the substrings between those separators. 286 // 287 // If s does not contain sep and sep is not empty, Split returns a 288 // slice of length 1 whose only element is s. 289 // 290 // If sep is empty, Split splits after each UTF-8 sequence. If both s 291 // and sep are empty, Split returns an empty slice. 292 // 293 // It is equivalent to SplitN with a count of -1. 294 func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) } 295 296 // SplitAfter slices s into all substrings after each instance of sep and 297 // returns a slice of those substrings. 298 // 299 // If s does not contain sep and sep is not empty, SplitAfter returns 300 // a slice of length 1 whose only element is s. 301 // 302 // If sep is empty, SplitAfter splits after each UTF-8 sequence. If 303 // both s and sep are empty, SplitAfter returns an empty slice. 304 // 305 // It is equivalent to SplitAfterN with a count of -1. 306 func SplitAfter(s, sep string) []string { 307 return genSplit(s, sep, len(sep), -1) 308 } 309 310 var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1} 311 312 // Fields splits the string s around each instance of one or more consecutive white space 313 // characters, as defined by unicode.IsSpace, returning an array of substrings of s or an 314 // empty list if s contains only white space. 315 func Fields(s string) []string { 316 // First count the fields. 317 // This is an exact count if s is ASCII, otherwise it is an approximation. 318 n := 0 319 wasSpace := 1 320 // setBits is used to track which bits are set in the bytes of s. 321 setBits := uint8(0) 322 for i := 0; i < len(s); i++ { 323 r := s[i] 324 setBits |= r 325 isSpace := int(asciiSpace[r]) 326 n += wasSpace & ^isSpace 327 wasSpace = isSpace 328 } 329 330 if setBits < utf8.RuneSelf { // ASCII fast path 331 a := make([]string, n) 332 na := 0 333 fieldStart := 0 334 i := 0 335 // Skip spaces in the front of the input. 336 for i < len(s) && asciiSpace[s[i]] != 0 { 337 i++ 338 } 339 fieldStart = i 340 for i < len(s) { 341 if asciiSpace[s[i]] == 0 { 342 i++ 343 continue 344 } 345 a[na] = s[fieldStart:i] 346 na++ 347 i++ 348 // Skip spaces in between fields. 349 for i < len(s) && asciiSpace[s[i]] != 0 { 350 i++ 351 } 352 fieldStart = i 353 } 354 if fieldStart < len(s) { // Last field might end at EOF. 355 a[na] = s[fieldStart:] 356 } 357 return a 358 } 359 360 // Some runes in the input string are not ASCII. 361 // Same general approach as in the ASCII path but 362 // uses DecodeRuneInString and unicode.IsSpace if 363 // a non-ASCII rune needs to be decoded and checked 364 // if it corresponds to a space. 365 a := make([]string, 0, n) 366 i := 0 367 // Skip spaces in the front of the input. 368 for i < len(s) { 369 if c := s[i]; c < utf8.RuneSelf { 370 if asciiSpace[c] == 0 { 371 break 372 } 373 i++ 374 } else { 375 r, w := utf8.DecodeRuneInString(s[i:]) 376 if !unicode.IsSpace(r) { 377 break 378 } 379 i += w 380 } 381 } 382 fieldStart := i 383 for i < len(s) { 384 if c := s[i]; c < utf8.RuneSelf { 385 if asciiSpace[c] == 0 { 386 i++ 387 continue 388 } 389 a = append(a, s[fieldStart:i]) 390 i++ 391 } else { 392 r, w := utf8.DecodeRuneInString(s[i:]) 393 if !unicode.IsSpace(r) { 394 i += w 395 continue 396 } 397 a = append(a, s[fieldStart:i]) 398 i += w 399 } 400 // Skip spaces in between fields. 401 for i < len(s) { 402 if c := s[i]; c < utf8.RuneSelf { 403 if asciiSpace[c] == 0 { 404 break 405 } 406 i++ 407 } else { 408 r, w := utf8.DecodeRuneInString(s[i:]) 409 if !unicode.IsSpace(r) { 410 break 411 } 412 i += w 413 } 414 } 415 fieldStart = i 416 } 417 if fieldStart < len(s) { // Last field might end at EOF. 418 a = append(a, s[fieldStart:]) 419 } 420 return a 421 } 422 423 // FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c) 424 // and returns an array of slices of s. If all code points in s satisfy f(c) or the 425 // string is empty, an empty slice is returned. 426 // FieldsFunc makes no guarantees about the order in which it calls f(c). 427 // If f does not return consistent results for a given c, FieldsFunc may crash. 428 func FieldsFunc(s string, f func(rune) bool) []string { 429 // First count the fields. 430 n := 0 431 inField := false 432 for _, rune := range s { 433 wasInField := inField 434 inField = !f(rune) 435 if inField && !wasInField { 436 n++ 437 } 438 } 439 440 // Now create them. 441 a := make([]string, n) 442 na := 0 443 fieldStart := -1 // Set to -1 when looking for start of field. 444 for i, rune := range s { 445 if f(rune) { 446 if fieldStart >= 0 { 447 a[na] = s[fieldStart:i] 448 na++ 449 fieldStart = -1 450 } 451 } else if fieldStart == -1 { 452 fieldStart = i 453 } 454 } 455 if fieldStart >= 0 { // Last field might end at EOF. 456 a[na] = s[fieldStart:] 457 } 458 return a 459 } 460 461 // Join concatenates the elements of a to create a single string. The separator string 462 // sep is placed between elements in the resulting string. 463 func Join(a []string, sep string) string { 464 switch len(a) { 465 case 0: 466 return "" 467 case 1: 468 return a[0] 469 case 2: 470 // Special case for common small values. 471 // Remove if golang.org/issue/6714 is fixed 472 return a[0] + sep + a[1] 473 case 3: 474 // Special case for common small values. 475 // Remove if golang.org/issue/6714 is fixed 476 return a[0] + sep + a[1] + sep + a[2] 477 } 478 n := len(sep) * (len(a) - 1) 479 for i := 0; i < len(a); i++ { 480 n += len(a[i]) 481 } 482 483 b := make([]byte, n) 484 bp := copy(b, a[0]) 485 for _, s := range a[1:] { 486 bp += copy(b[bp:], sep) 487 bp += copy(b[bp:], s) 488 } 489 return string(b) 490 } 491 492 // HasPrefix tests whether the string s begins with prefix. 493 func HasPrefix(s, prefix string) bool { 494 return len(s) >= len(prefix) && s[0:len(prefix)] == prefix 495 } 496 497 // HasSuffix tests whether the string s ends with suffix. 498 func HasSuffix(s, suffix string) bool { 499 return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix 500 } 501 502 // Map returns a copy of the string s with all its characters modified 503 // according to the mapping function. If mapping returns a negative value, the character is 504 // dropped from the string with no replacement. 505 func Map(mapping func(rune) rune, s string) string { 506 // In the worst case, the string can grow when mapped, making 507 // things unpleasant. But it's so rare we barge in assuming it's 508 // fine. It could also shrink but that falls out naturally. 509 510 // The output buffer b is initialized on demand, the first 511 // time a character differs. 512 var b []byte 513 // nbytes is the number of bytes encoded in b. 514 var nbytes int 515 516 for i, c := range s { 517 r := mapping(c) 518 if r == c { 519 continue 520 } 521 522 b = make([]byte, len(s)+utf8.UTFMax) 523 nbytes = copy(b, s[:i]) 524 if r >= 0 { 525 if r <= utf8.RuneSelf { 526 b[nbytes] = byte(r) 527 nbytes++ 528 } else { 529 nbytes += utf8.EncodeRune(b[nbytes:], r) 530 } 531 } 532 533 if c == utf8.RuneError { 534 // RuneError is the result of either decoding 535 // an invalid sequence or '\uFFFD'. Determine 536 // the correct number of bytes we need to advance. 537 _, w := utf8.DecodeRuneInString(s[i:]) 538 i += w 539 } else { 540 i += utf8.RuneLen(c) 541 } 542 543 s = s[i:] 544 break 545 } 546 547 if b == nil { 548 return s 549 } 550 551 for _, c := range s { 552 r := mapping(c) 553 554 // common case 555 if (0 <= r && r <= utf8.RuneSelf) && nbytes < len(b) { 556 b[nbytes] = byte(r) 557 nbytes++ 558 continue 559 } 560 561 // b is not big enough or r is not a ASCII rune. 562 if r >= 0 { 563 if nbytes+utf8.UTFMax >= len(b) { 564 // Grow the buffer. 565 nb := make([]byte, 2*len(b)) 566 copy(nb, b[:nbytes]) 567 b = nb 568 } 569 nbytes += utf8.EncodeRune(b[nbytes:], r) 570 } 571 } 572 573 return string(b[:nbytes]) 574 } 575 576 // Repeat returns a new string consisting of count copies of the string s. 577 // 578 // It panics if count is negative or if 579 // the result of (len(s) * count) overflows. 580 func Repeat(s string, count int) string { 581 // Since we cannot return an error on overflow, 582 // we should panic if the repeat will generate 583 // an overflow. 584 // See Issue golang.org/issue/16237 585 if count < 0 { 586 panic("strings: negative Repeat count") 587 } else if count > 0 && len(s)*count/count != len(s) { 588 panic("strings: Repeat count causes overflow") 589 } 590 591 b := make([]byte, len(s)*count) 592 bp := copy(b, s) 593 for bp < len(b) { 594 copy(b[bp:], b[:bp]) 595 bp *= 2 596 } 597 return string(b) 598 } 599 600 // ToUpper returns a copy of the string s with all Unicode letters mapped to their upper case. 601 func ToUpper(s string) string { return Map(unicode.ToUpper, s) } 602 603 // ToLower returns a copy of the string s with all Unicode letters mapped to their lower case. 604 func ToLower(s string) string { return Map(unicode.ToLower, s) } 605 606 // ToTitle returns a copy of the string s with all Unicode letters mapped to their title case. 607 func ToTitle(s string) string { return Map(unicode.ToTitle, s) } 608 609 // ToUpperSpecial returns a copy of the string s with all Unicode letters mapped to their 610 // upper case, giving priority to the special casing rules. 611 func ToUpperSpecial(c unicode.SpecialCase, s string) string { 612 return Map(func(r rune) rune { return c.ToUpper(r) }, s) 613 } 614 615 // ToLowerSpecial returns a copy of the string s with all Unicode letters mapped to their 616 // lower case, giving priority to the special casing rules. 617 func ToLowerSpecial(c unicode.SpecialCase, s string) string { 618 return Map(func(r rune) rune { return c.ToLower(r) }, s) 619 } 620 621 // ToTitleSpecial returns a copy of the string s with all Unicode letters mapped to their 622 // title case, giving priority to the special casing rules. 623 func ToTitleSpecial(c unicode.SpecialCase, s string) string { 624 return Map(func(r rune) rune { return c.ToTitle(r) }, s) 625 } 626 627 // isSeparator reports whether the rune could mark a word boundary. 628 // TODO: update when package unicode captures more of the properties. 629 func isSeparator(r rune) bool { 630 // ASCII alphanumerics and underscore are not separators 631 if r <= 0x7F { 632 switch { 633 case '0' <= r && r <= '9': 634 return false 635 case 'a' <= r && r <= 'z': 636 return false 637 case 'A' <= r && r <= 'Z': 638 return false 639 case r == '_': 640 return false 641 } 642 return true 643 } 644 // Letters and digits are not separators 645 if unicode.IsLetter(r) || unicode.IsDigit(r) { 646 return false 647 } 648 // Otherwise, all we can do for now is treat spaces as separators. 649 return unicode.IsSpace(r) 650 } 651 652 // Title returns a copy of the string s with all Unicode letters that begin words 653 // mapped to their title case. 654 // 655 // BUG(rsc): The rule Title uses for word boundaries does not handle Unicode punctuation properly. 656 func Title(s string) string { 657 // Use a closure here to remember state. 658 // Hackish but effective. Depends on Map scanning in order and calling 659 // the closure once per rune. 660 prev := ' ' 661 return Map( 662 func(r rune) rune { 663 if isSeparator(prev) { 664 prev = r 665 return unicode.ToTitle(r) 666 } 667 prev = r 668 return r 669 }, 670 s) 671 } 672 673 // TrimLeftFunc returns a slice of the string s with all leading 674 // Unicode code points c satisfying f(c) removed. 675 func TrimLeftFunc(s string, f func(rune) bool) string { 676 i := indexFunc(s, f, false) 677 if i == -1 { 678 return "" 679 } 680 return s[i:] 681 } 682 683 // TrimRightFunc returns a slice of the string s with all trailing 684 // Unicode code points c satisfying f(c) removed. 685 func TrimRightFunc(s string, f func(rune) bool) string { 686 i := lastIndexFunc(s, f, false) 687 if i >= 0 && s[i] >= utf8.RuneSelf { 688 _, wid := utf8.DecodeRuneInString(s[i:]) 689 i += wid 690 } else { 691 i++ 692 } 693 return s[0:i] 694 } 695 696 // TrimFunc returns a slice of the string s with all leading 697 // and trailing Unicode code points c satisfying f(c) removed. 698 func TrimFunc(s string, f func(rune) bool) string { 699 return TrimRightFunc(TrimLeftFunc(s, f), f) 700 } 701 702 // IndexFunc returns the index into s of the first Unicode 703 // code point satisfying f(c), or -1 if none do. 704 func IndexFunc(s string, f func(rune) bool) int { 705 return indexFunc(s, f, true) 706 } 707 708 // LastIndexFunc returns the index into s of the last 709 // Unicode code point satisfying f(c), or -1 if none do. 710 func LastIndexFunc(s string, f func(rune) bool) int { 711 return lastIndexFunc(s, f, true) 712 } 713 714 // indexFunc is the same as IndexFunc except that if 715 // truth==false, the sense of the predicate function is 716 // inverted. 717 func indexFunc(s string, f func(rune) bool, truth bool) int { 718 for i, r := range s { 719 if f(r) == truth { 720 return i 721 } 722 } 723 return -1 724 } 725 726 // lastIndexFunc is the same as LastIndexFunc except that if 727 // truth==false, the sense of the predicate function is 728 // inverted. 729 func lastIndexFunc(s string, f func(rune) bool, truth bool) int { 730 for i := len(s); i > 0; { 731 r, size := utf8.DecodeLastRuneInString(s[0:i]) 732 i -= size 733 if f(r) == truth { 734 return i 735 } 736 } 737 return -1 738 } 739 740 // asciiSet is a 32-byte value, where each bit represents the presence of a 741 // given ASCII character in the set. The 128-bits of the lower 16 bytes, 742 // starting with the least-significant bit of the lowest word to the 743 // most-significant bit of the highest word, map to the full range of all 744 // 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed, 745 // ensuring that any non-ASCII character will be reported as not in the set. 746 type asciiSet [8]uint32 747 748 // makeASCIISet creates a set of ASCII characters and reports whether all 749 // characters in chars are ASCII. 750 func makeASCIISet(chars string) (as asciiSet, ok bool) { 751 for i := 0; i < len(chars); i++ { 752 c := chars[i] 753 if c >= utf8.RuneSelf { 754 return as, false 755 } 756 as[c>>5] |= 1 << uint(c&31) 757 } 758 return as, true 759 } 760 761 // contains reports whether c is inside the set. 762 func (as *asciiSet) contains(c byte) bool { 763 return (as[c>>5] & (1 << uint(c&31))) != 0 764 } 765 766 func makeCutsetFunc(cutset string) func(rune) bool { 767 if len(cutset) == 1 && cutset[0] < utf8.RuneSelf { 768 return func(r rune) bool { 769 return r == rune(cutset[0]) 770 } 771 } 772 if as, isASCII := makeASCIISet(cutset); isASCII { 773 return func(r rune) bool { 774 return r < utf8.RuneSelf && as.contains(byte(r)) 775 } 776 } 777 return func(r rune) bool { return IndexRune(cutset, r) >= 0 } 778 } 779 780 // Trim returns a slice of the string s with all leading and 781 // trailing Unicode code points contained in cutset removed. 782 func Trim(s string, cutset string) string { 783 if s == "" || cutset == "" { 784 return s 785 } 786 return TrimFunc(s, makeCutsetFunc(cutset)) 787 } 788 789 // TrimLeft returns a slice of the string s with all leading 790 // Unicode code points contained in cutset removed. 791 func TrimLeft(s string, cutset string) string { 792 if s == "" || cutset == "" { 793 return s 794 } 795 return TrimLeftFunc(s, makeCutsetFunc(cutset)) 796 } 797 798 // TrimRight returns a slice of the string s, with all trailing 799 // Unicode code points contained in cutset removed. 800 func TrimRight(s string, cutset string) string { 801 if s == "" || cutset == "" { 802 return s 803 } 804 return TrimRightFunc(s, makeCutsetFunc(cutset)) 805 } 806 807 // TrimSpace returns a slice of the string s, with all leading 808 // and trailing white space removed, as defined by Unicode. 809 func TrimSpace(s string) string { 810 return TrimFunc(s, unicode.IsSpace) 811 } 812 813 // TrimPrefix returns s without the provided leading prefix string. 814 // If s doesn't start with prefix, s is returned unchanged. 815 func TrimPrefix(s, prefix string) string { 816 if HasPrefix(s, prefix) { 817 return s[len(prefix):] 818 } 819 return s 820 } 821 822 // TrimSuffix returns s without the provided trailing suffix string. 823 // If s doesn't end with suffix, s is returned unchanged. 824 func TrimSuffix(s, suffix string) string { 825 if HasSuffix(s, suffix) { 826 return s[:len(s)-len(suffix)] 827 } 828 return s 829 } 830 831 // Replace returns a copy of the string s with the first n 832 // non-overlapping instances of old replaced by new. 833 // If old is empty, it matches at the beginning of the string 834 // and after each UTF-8 sequence, yielding up to k+1 replacements 835 // for a k-rune string. 836 // If n < 0, there is no limit on the number of replacements. 837 func Replace(s, old, new string, n int) string { 838 if old == new || n == 0 { 839 return s // avoid allocation 840 } 841 842 // Compute number of replacements. 843 if m := Count(s, old); m == 0 { 844 return s // avoid allocation 845 } else if n < 0 || m < n { 846 n = m 847 } 848 849 // Apply replacements to buffer. 850 t := make([]byte, len(s)+n*(len(new)-len(old))) 851 w := 0 852 start := 0 853 for i := 0; i < n; i++ { 854 j := start 855 if len(old) == 0 { 856 if i > 0 { 857 _, wid := utf8.DecodeRuneInString(s[start:]) 858 j += wid 859 } 860 } else { 861 j += Index(s[start:], old) 862 } 863 w += copy(t[w:], s[start:j]) 864 w += copy(t[w:], new) 865 start = j + len(old) 866 } 867 w += copy(t[w:], s[start:]) 868 return string(t[0:w]) 869 } 870 871 // EqualFold reports whether s and t, interpreted as UTF-8 strings, 872 // are equal under Unicode case-folding. 873 func EqualFold(s, t string) bool { 874 for s != "" && t != "" { 875 // Extract first rune from each string. 876 var sr, tr rune 877 if s[0] < utf8.RuneSelf { 878 sr, s = rune(s[0]), s[1:] 879 } else { 880 r, size := utf8.DecodeRuneInString(s) 881 sr, s = r, s[size:] 882 } 883 if t[0] < utf8.RuneSelf { 884 tr, t = rune(t[0]), t[1:] 885 } else { 886 r, size := utf8.DecodeRuneInString(t) 887 tr, t = r, t[size:] 888 } 889 890 // If they match, keep going; if not, return false. 891 892 // Easy case. 893 if tr == sr { 894 continue 895 } 896 897 // Make sr < tr to simplify what follows. 898 if tr < sr { 899 tr, sr = sr, tr 900 } 901 // Fast check for ASCII. 902 if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' { 903 // ASCII, and sr is upper case. tr must be lower case. 904 if tr == sr+'a'-'A' { 905 continue 906 } 907 return false 908 } 909 910 // General case. SimpleFold(x) returns the next equivalent rune > x 911 // or wraps around to smaller values. 912 r := unicode.SimpleFold(sr) 913 for r != sr && r < tr { 914 r = unicode.SimpleFold(r) 915 } 916 if r == tr { 917 continue 918 } 919 return false 920 } 921 922 // One string is empty. Are both? 923 return s == t 924 }