rsc.io/go@v0.0.0-20150416155037-e040fd465409/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 strings. 6 package strings 7 8 import ( 9 "unicode" 10 "unicode/utf8" 11 ) 12 13 // explode splits s into an array of UTF-8 sequences, one per Unicode character (still strings) up to a maximum of n (n < 0 means no limit). 14 // Invalid UTF-8 sequences become correct encodings of U+FFF8. 15 func explode(s string, n int) []string { 16 if n == 0 { 17 return nil 18 } 19 l := utf8.RuneCountInString(s) 20 if n <= 0 || n > l { 21 n = l 22 } 23 a := make([]string, n) 24 var size int 25 var ch rune 26 i, cur := 0, 0 27 for ; i+1 < n; i++ { 28 ch, size = utf8.DecodeRuneInString(s[cur:]) 29 if ch == utf8.RuneError { 30 a[i] = string(utf8.RuneError) 31 } else { 32 a[i] = s[cur : cur+size] 33 } 34 cur += size 35 } 36 // add the rest, if there is any 37 if cur < len(s) { 38 a[i] = s[cur:] 39 } 40 return a 41 } 42 43 // primeRK is the prime base used in Rabin-Karp algorithm. 44 const primeRK = 16777619 45 46 // hashStr returns the hash and the appropriate multiplicative 47 // factor for use in Rabin-Karp algorithm. 48 func hashStr(sep string) (uint32, uint32) { 49 hash := uint32(0) 50 for i := 0; i < len(sep); i++ { 51 hash = hash*primeRK + uint32(sep[i]) 52 } 53 var pow, sq uint32 = 1, primeRK 54 for i := len(sep); i > 0; i >>= 1 { 55 if i&1 != 0 { 56 pow *= sq 57 } 58 sq *= sq 59 } 60 return hash, pow 61 } 62 63 // hashStrRev returns the hash of the reverse of sep and the 64 // appropriate multiplicative factor for use in Rabin-Karp algorithm. 65 func hashStrRev(sep string) (uint32, uint32) { 66 hash := uint32(0) 67 for i := len(sep) - 1; i >= 0; i-- { 68 hash = hash*primeRK + uint32(sep[i]) 69 } 70 var pow, sq uint32 = 1, primeRK 71 for i := len(sep); i > 0; i >>= 1 { 72 if i&1 != 0 { 73 pow *= sq 74 } 75 sq *= sq 76 } 77 return hash, pow 78 } 79 80 // Count counts the number of non-overlapping instances of sep in s. 81 // If sep is an empty string, Count returns 1 + the number of Unicode code points in s. 82 func Count(s, sep string) int { 83 n := 0 84 // special cases 85 switch { 86 case len(sep) == 0: 87 return utf8.RuneCountInString(s) + 1 88 case len(sep) == 1: 89 // special case worth making fast 90 c := sep[0] 91 for i := 0; i < len(s); i++ { 92 if s[i] == c { 93 n++ 94 } 95 } 96 return n 97 case len(sep) > len(s): 98 return 0 99 case len(sep) == len(s): 100 if sep == s { 101 return 1 102 } 103 return 0 104 } 105 // Rabin-Karp search 106 hashsep, pow := hashStr(sep) 107 h := uint32(0) 108 for i := 0; i < len(sep); i++ { 109 h = h*primeRK + uint32(s[i]) 110 } 111 lastmatch := 0 112 if h == hashsep && s[:len(sep)] == sep { 113 n++ 114 lastmatch = len(sep) 115 } 116 for i := len(sep); i < len(s); { 117 h *= primeRK 118 h += uint32(s[i]) 119 h -= pow * uint32(s[i-len(sep)]) 120 i++ 121 if h == hashsep && lastmatch <= i-len(sep) && s[i-len(sep):i] == sep { 122 n++ 123 lastmatch = i 124 } 125 } 126 return n 127 } 128 129 // Contains reports whether substr is within s. 130 func Contains(s, substr string) bool { 131 return Index(s, substr) >= 0 132 } 133 134 // ContainsAny reports whether any Unicode code points in chars are within s. 135 func ContainsAny(s, chars string) bool { 136 return IndexAny(s, chars) >= 0 137 } 138 139 // ContainsRune reports whether the Unicode code point r is within s. 140 func ContainsRune(s string, r rune) bool { 141 return IndexRune(s, r) >= 0 142 } 143 144 // Index returns the index of the first instance of sep in s, or -1 if sep is not present in s. 145 func Index(s, sep string) int { 146 n := len(sep) 147 switch { 148 case n == 0: 149 return 0 150 case n == 1: 151 return IndexByte(s, sep[0]) 152 case n == len(s): 153 if sep == s { 154 return 0 155 } 156 return -1 157 case n > len(s): 158 return -1 159 } 160 // Rabin-Karp search 161 hashsep, pow := hashStr(sep) 162 var h uint32 163 for i := 0; i < n; i++ { 164 h = h*primeRK + uint32(s[i]) 165 } 166 if h == hashsep && s[:n] == sep { 167 return 0 168 } 169 for i := n; i < len(s); { 170 h *= primeRK 171 h += uint32(s[i]) 172 h -= pow * uint32(s[i-n]) 173 i++ 174 if h == hashsep && s[i-n:i] == sep { 175 return i - n 176 } 177 } 178 return -1 179 } 180 181 // LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s. 182 func LastIndex(s, sep string) int { 183 n := len(sep) 184 switch { 185 case n == 0: 186 return len(s) 187 case n == 1: 188 // special case worth making fast 189 c := sep[0] 190 for i := len(s) - 1; i >= 0; i-- { 191 if s[i] == c { 192 return i 193 } 194 } 195 return -1 196 case n == len(s): 197 if sep == s { 198 return 0 199 } 200 return -1 201 case n > len(s): 202 return -1 203 } 204 // Rabin-Karp search from the end of the string 205 hashsep, pow := hashStrRev(sep) 206 last := len(s) - n 207 var h uint32 208 for i := len(s) - 1; i >= last; i-- { 209 h = h*primeRK + uint32(s[i]) 210 } 211 if h == hashsep && s[last:] == sep { 212 return last 213 } 214 for i := last - 1; i >= 0; i-- { 215 h *= primeRK 216 h += uint32(s[i]) 217 h -= pow * uint32(s[i+n]) 218 if h == hashsep && s[i:i+n] == sep { 219 return i 220 } 221 } 222 return -1 223 } 224 225 // IndexRune returns the index of the first instance of the Unicode code point 226 // r, or -1 if rune is not present in s. 227 func IndexRune(s string, r rune) int { 228 switch { 229 case r < utf8.RuneSelf: 230 return IndexByte(s, byte(r)) 231 default: 232 for i, c := range s { 233 if c == r { 234 return i 235 } 236 } 237 } 238 return -1 239 } 240 241 // IndexAny returns the index of the first instance of any Unicode code point 242 // from chars in s, or -1 if no Unicode code point from chars is present in s. 243 func IndexAny(s, chars string) int { 244 if len(chars) > 0 { 245 for i, c := range s { 246 for _, m := range chars { 247 if c == m { 248 return i 249 } 250 } 251 } 252 } 253 return -1 254 } 255 256 // LastIndexAny returns the index of the last instance of any Unicode code 257 // point from chars in s, or -1 if no Unicode code point from chars is 258 // present in s. 259 func LastIndexAny(s, chars string) int { 260 if len(chars) > 0 { 261 for i := len(s); i > 0; { 262 rune, size := utf8.DecodeLastRuneInString(s[0:i]) 263 i -= size 264 for _, m := range chars { 265 if rune == m { 266 return i 267 } 268 } 269 } 270 } 271 return -1 272 } 273 274 // Generic split: splits after each instance of sep, 275 // including sepSave bytes of sep in the subarrays. 276 func genSplit(s, sep string, sepSave, n int) []string { 277 if n == 0 { 278 return nil 279 } 280 if sep == "" { 281 return explode(s, n) 282 } 283 if n < 0 { 284 n = Count(s, sep) + 1 285 } 286 c := sep[0] 287 start := 0 288 a := make([]string, n) 289 na := 0 290 for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ { 291 if s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) { 292 a[na] = s[start : i+sepSave] 293 na++ 294 start = i + len(sep) 295 i += len(sep) - 1 296 } 297 } 298 a[na] = s[start:] 299 return a[0 : na+1] 300 } 301 302 // SplitN slices s into substrings separated by sep and returns a slice of 303 // the substrings between those separators. 304 // If sep is empty, SplitN splits after each UTF-8 sequence. 305 // The count determines the number of substrings to return: 306 // n > 0: at most n substrings; the last substring will be the unsplit remainder. 307 // n == 0: the result is nil (zero substrings) 308 // n < 0: all substrings 309 func SplitN(s, sep string, n int) []string { return genSplit(s, sep, 0, n) } 310 311 // SplitAfterN slices s into substrings after each instance of sep and 312 // returns a slice of those substrings. 313 // If sep is empty, SplitAfterN splits after each UTF-8 sequence. 314 // The count determines the number of substrings to return: 315 // n > 0: at most n substrings; the last substring will be the unsplit remainder. 316 // n == 0: the result is nil (zero substrings) 317 // n < 0: all substrings 318 func SplitAfterN(s, sep string, n int) []string { 319 return genSplit(s, sep, len(sep), n) 320 } 321 322 // Split slices s into all substrings separated by sep and returns a slice of 323 // the substrings between those separators. 324 // If sep is empty, Split splits after each UTF-8 sequence. 325 // It is equivalent to SplitN with a count of -1. 326 func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) } 327 328 // SplitAfter slices s into all substrings after each instance of sep and 329 // returns a slice of those substrings. 330 // If sep is empty, SplitAfter splits after each UTF-8 sequence. 331 // It is equivalent to SplitAfterN with a count of -1. 332 func SplitAfter(s, sep string) []string { 333 return genSplit(s, sep, len(sep), -1) 334 } 335 336 // Fields splits the string s around each instance of one or more consecutive white space 337 // characters, as defined by unicode.IsSpace, returning an array of substrings of s or an 338 // empty list if s contains only white space. 339 func Fields(s string) []string { 340 return FieldsFunc(s, unicode.IsSpace) 341 } 342 343 // FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c) 344 // and returns an array of slices of s. If all code points in s satisfy f(c) or the 345 // string is empty, an empty slice is returned. 346 // FieldsFunc makes no guarantees about the order in which it calls f(c). 347 // If f does not return consistent results for a given c, FieldsFunc may crash. 348 func FieldsFunc(s string, f func(rune) bool) []string { 349 // First count the fields. 350 n := 0 351 inField := false 352 for _, rune := range s { 353 wasInField := inField 354 inField = !f(rune) 355 if inField && !wasInField { 356 n++ 357 } 358 } 359 360 // Now create them. 361 a := make([]string, n) 362 na := 0 363 fieldStart := -1 // Set to -1 when looking for start of field. 364 for i, rune := range s { 365 if f(rune) { 366 if fieldStart >= 0 { 367 a[na] = s[fieldStart:i] 368 na++ 369 fieldStart = -1 370 } 371 } else if fieldStart == -1 { 372 fieldStart = i 373 } 374 } 375 if fieldStart >= 0 { // Last field might end at EOF. 376 a[na] = s[fieldStart:] 377 } 378 return a 379 } 380 381 // Join concatenates the elements of a to create a single string. The separator string 382 // sep is placed between elements in the resulting string. 383 func Join(a []string, sep string) string { 384 if len(a) == 0 { 385 return "" 386 } 387 if len(a) == 1 { 388 return a[0] 389 } 390 n := len(sep) * (len(a) - 1) 391 for i := 0; i < len(a); i++ { 392 n += len(a[i]) 393 } 394 395 b := make([]byte, n) 396 bp := copy(b, a[0]) 397 for _, s := range a[1:] { 398 bp += copy(b[bp:], sep) 399 bp += copy(b[bp:], s) 400 } 401 return string(b) 402 } 403 404 // HasPrefix tests whether the string s begins with prefix. 405 func HasPrefix(s, prefix string) bool { 406 return len(s) >= len(prefix) && s[0:len(prefix)] == prefix 407 } 408 409 // HasSuffix tests whether the string s ends with suffix. 410 func HasSuffix(s, suffix string) bool { 411 return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix 412 } 413 414 // Map returns a copy of the string s with all its characters modified 415 // according to the mapping function. If mapping returns a negative value, the character is 416 // dropped from the string with no replacement. 417 func Map(mapping func(rune) rune, s string) string { 418 // In the worst case, the string can grow when mapped, making 419 // things unpleasant. But it's so rare we barge in assuming it's 420 // fine. It could also shrink but that falls out naturally. 421 maxbytes := len(s) // length of b 422 nbytes := 0 // number of bytes encoded in b 423 // The output buffer b is initialized on demand, the first 424 // time a character differs. 425 var b []byte 426 427 for i, c := range s { 428 r := mapping(c) 429 if b == nil { 430 if r == c { 431 continue 432 } 433 b = make([]byte, maxbytes) 434 nbytes = copy(b, s[:i]) 435 } 436 if r >= 0 { 437 wid := 1 438 if r >= utf8.RuneSelf { 439 wid = utf8.RuneLen(r) 440 } 441 if nbytes+wid > maxbytes { 442 // Grow the buffer. 443 maxbytes = maxbytes*2 + utf8.UTFMax 444 nb := make([]byte, maxbytes) 445 copy(nb, b[0:nbytes]) 446 b = nb 447 } 448 nbytes += utf8.EncodeRune(b[nbytes:maxbytes], r) 449 } 450 } 451 if b == nil { 452 return s 453 } 454 return string(b[0:nbytes]) 455 } 456 457 // Repeat returns a new string consisting of count copies of the string s. 458 func Repeat(s string, count int) string { 459 b := make([]byte, len(s)*count) 460 bp := copy(b, s) 461 for bp < len(b) { 462 copy(b[bp:], b[:bp]) 463 bp *= 2 464 } 465 return string(b) 466 } 467 468 // ToUpper returns a copy of the string s with all Unicode letters mapped to their upper case. 469 func ToUpper(s string) string { return Map(unicode.ToUpper, s) } 470 471 // ToLower returns a copy of the string s with all Unicode letters mapped to their lower case. 472 func ToLower(s string) string { return Map(unicode.ToLower, s) } 473 474 // ToTitle returns a copy of the string s with all Unicode letters mapped to their title case. 475 func ToTitle(s string) string { return Map(unicode.ToTitle, s) } 476 477 // ToUpperSpecial returns a copy of the string s with all Unicode letters mapped to their 478 // upper case, giving priority to the special casing rules. 479 func ToUpperSpecial(_case unicode.SpecialCase, s string) string { 480 return Map(func(r rune) rune { return _case.ToUpper(r) }, s) 481 } 482 483 // ToLowerSpecial returns a copy of the string s with all Unicode letters mapped to their 484 // lower case, giving priority to the special casing rules. 485 func ToLowerSpecial(_case unicode.SpecialCase, s string) string { 486 return Map(func(r rune) rune { return _case.ToLower(r) }, s) 487 } 488 489 // ToTitleSpecial returns a copy of the string s with all Unicode letters mapped to their 490 // title case, giving priority to the special casing rules. 491 func ToTitleSpecial(_case unicode.SpecialCase, s string) string { 492 return Map(func(r rune) rune { return _case.ToTitle(r) }, s) 493 } 494 495 // isSeparator reports whether the rune could mark a word boundary. 496 // TODO: update when package unicode captures more of the properties. 497 func isSeparator(r rune) bool { 498 // ASCII alphanumerics and underscore are not separators 499 if r <= 0x7F { 500 switch { 501 case '0' <= r && r <= '9': 502 return false 503 case 'a' <= r && r <= 'z': 504 return false 505 case 'A' <= r && r <= 'Z': 506 return false 507 case r == '_': 508 return false 509 } 510 return true 511 } 512 // Letters and digits are not separators 513 if unicode.IsLetter(r) || unicode.IsDigit(r) { 514 return false 515 } 516 // Otherwise, all we can do for now is treat spaces as separators. 517 return unicode.IsSpace(r) 518 } 519 520 // Title returns a copy of the string s with all Unicode letters that begin words 521 // mapped to their title case. 522 // 523 // BUG(rsc): The rule Title uses for word boundaries does not handle Unicode punctuation properly. 524 func Title(s string) string { 525 // Use a closure here to remember state. 526 // Hackish but effective. Depends on Map scanning in order and calling 527 // the closure once per rune. 528 prev := ' ' 529 return Map( 530 func(r rune) rune { 531 if isSeparator(prev) { 532 prev = r 533 return unicode.ToTitle(r) 534 } 535 prev = r 536 return r 537 }, 538 s) 539 } 540 541 // TrimLeftFunc returns a slice of the string s with all leading 542 // Unicode code points c satisfying f(c) removed. 543 func TrimLeftFunc(s string, f func(rune) bool) string { 544 i := indexFunc(s, f, false) 545 if i == -1 { 546 return "" 547 } 548 return s[i:] 549 } 550 551 // TrimRightFunc returns a slice of the string s with all trailing 552 // Unicode code points c satisfying f(c) removed. 553 func TrimRightFunc(s string, f func(rune) bool) string { 554 i := lastIndexFunc(s, f, false) 555 if i >= 0 && s[i] >= utf8.RuneSelf { 556 _, wid := utf8.DecodeRuneInString(s[i:]) 557 i += wid 558 } else { 559 i++ 560 } 561 return s[0:i] 562 } 563 564 // TrimFunc returns a slice of the string s with all leading 565 // and trailing Unicode code points c satisfying f(c) removed. 566 func TrimFunc(s string, f func(rune) bool) string { 567 return TrimRightFunc(TrimLeftFunc(s, f), f) 568 } 569 570 // IndexFunc returns the index into s of the first Unicode 571 // code point satisfying f(c), or -1 if none do. 572 func IndexFunc(s string, f func(rune) bool) int { 573 return indexFunc(s, f, true) 574 } 575 576 // LastIndexFunc returns the index into s of the last 577 // Unicode code point satisfying f(c), or -1 if none do. 578 func LastIndexFunc(s string, f func(rune) bool) int { 579 return lastIndexFunc(s, f, true) 580 } 581 582 // indexFunc is the same as IndexFunc except that if 583 // truth==false, the sense of the predicate function is 584 // inverted. 585 func indexFunc(s string, f func(rune) bool, truth bool) int { 586 start := 0 587 for start < len(s) { 588 wid := 1 589 r := rune(s[start]) 590 if r >= utf8.RuneSelf { 591 r, wid = utf8.DecodeRuneInString(s[start:]) 592 } 593 if f(r) == truth { 594 return start 595 } 596 start += wid 597 } 598 return -1 599 } 600 601 // lastIndexFunc is the same as LastIndexFunc except that if 602 // truth==false, the sense of the predicate function is 603 // inverted. 604 func lastIndexFunc(s string, f func(rune) bool, truth bool) int { 605 for i := len(s); i > 0; { 606 r, size := utf8.DecodeLastRuneInString(s[0:i]) 607 i -= size 608 if f(r) == truth { 609 return i 610 } 611 } 612 return -1 613 } 614 615 func makeCutsetFunc(cutset string) func(rune) bool { 616 return func(r rune) bool { return IndexRune(cutset, r) >= 0 } 617 } 618 619 // Trim returns a slice of the string s with all leading and 620 // trailing Unicode code points contained in cutset removed. 621 func Trim(s string, cutset string) string { 622 if s == "" || cutset == "" { 623 return s 624 } 625 return TrimFunc(s, makeCutsetFunc(cutset)) 626 } 627 628 // TrimLeft returns a slice of the string s with all leading 629 // Unicode code points contained in cutset removed. 630 func TrimLeft(s string, cutset string) string { 631 if s == "" || cutset == "" { 632 return s 633 } 634 return TrimLeftFunc(s, makeCutsetFunc(cutset)) 635 } 636 637 // TrimRight returns a slice of the string s, with all trailing 638 // Unicode code points contained in cutset removed. 639 func TrimRight(s string, cutset string) string { 640 if s == "" || cutset == "" { 641 return s 642 } 643 return TrimRightFunc(s, makeCutsetFunc(cutset)) 644 } 645 646 // TrimSpace returns a slice of the string s, with all leading 647 // and trailing white space removed, as defined by Unicode. 648 func TrimSpace(s string) string { 649 return TrimFunc(s, unicode.IsSpace) 650 } 651 652 // TrimPrefix returns s without the provided leading prefix string. 653 // If s doesn't start with prefix, s is returned unchanged. 654 func TrimPrefix(s, prefix string) string { 655 if HasPrefix(s, prefix) { 656 return s[len(prefix):] 657 } 658 return s 659 } 660 661 // TrimSuffix returns s without the provided trailing suffix string. 662 // If s doesn't end with suffix, s is returned unchanged. 663 func TrimSuffix(s, suffix string) string { 664 if HasSuffix(s, suffix) { 665 return s[:len(s)-len(suffix)] 666 } 667 return s 668 } 669 670 // Replace returns a copy of the string s with the first n 671 // non-overlapping instances of old replaced by new. 672 // If old is empty, it matches at the beginning of the string 673 // and after each UTF-8 sequence, yielding up to k+1 replacements 674 // for a k-rune string. 675 // If n < 0, there is no limit on the number of replacements. 676 func Replace(s, old, new string, n int) string { 677 if old == new || n == 0 { 678 return s // avoid allocation 679 } 680 681 // Compute number of replacements. 682 if m := Count(s, old); m == 0 { 683 return s // avoid allocation 684 } else if n < 0 || m < n { 685 n = m 686 } 687 688 // Apply replacements to buffer. 689 t := make([]byte, len(s)+n*(len(new)-len(old))) 690 w := 0 691 start := 0 692 for i := 0; i < n; i++ { 693 j := start 694 if len(old) == 0 { 695 if i > 0 { 696 _, wid := utf8.DecodeRuneInString(s[start:]) 697 j += wid 698 } 699 } else { 700 j += Index(s[start:], old) 701 } 702 w += copy(t[w:], s[start:j]) 703 w += copy(t[w:], new) 704 start = j + len(old) 705 } 706 w += copy(t[w:], s[start:]) 707 return string(t[0:w]) 708 } 709 710 // EqualFold reports whether s and t, interpreted as UTF-8 strings, 711 // are equal under Unicode case-folding. 712 func EqualFold(s, t string) bool { 713 for s != "" && t != "" { 714 // Extract first rune from each string. 715 var sr, tr rune 716 if s[0] < utf8.RuneSelf { 717 sr, s = rune(s[0]), s[1:] 718 } else { 719 r, size := utf8.DecodeRuneInString(s) 720 sr, s = r, s[size:] 721 } 722 if t[0] < utf8.RuneSelf { 723 tr, t = rune(t[0]), t[1:] 724 } else { 725 r, size := utf8.DecodeRuneInString(t) 726 tr, t = r, t[size:] 727 } 728 729 // If they match, keep going; if not, return false. 730 731 // Easy case. 732 if tr == sr { 733 continue 734 } 735 736 // Make sr < tr to simplify what follows. 737 if tr < sr { 738 tr, sr = sr, tr 739 } 740 // Fast check for ASCII. 741 if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' { 742 // ASCII, and sr is upper case. tr must be lower case. 743 if tr == sr+'a'-'A' { 744 continue 745 } 746 return false 747 } 748 749 // General case. SimpleFold(x) returns the next equivalent rune > x 750 // or wraps around to smaller values. 751 r := unicode.SimpleFold(sr) 752 for r != sr && r < tr { 753 r = unicode.SimpleFold(r) 754 } 755 if r == tr { 756 continue 757 } 758 return false 759 } 760 761 // One string is empty. Are both? 762 return s == t 763 }