github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/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 a slice of substrings of s or an 314 // empty slice 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 return FieldsFunc(s, unicode.IsSpace) 362 } 363 364 // FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c) 365 // and returns an array of slices of s. If all code points in s satisfy f(c) or the 366 // string is empty, an empty slice is returned. 367 // FieldsFunc makes no guarantees about the order in which it calls f(c). 368 // If f does not return consistent results for a given c, FieldsFunc may crash. 369 func FieldsFunc(s string, f func(rune) bool) []string { 370 // A span is used to record a slice of s of the form s[start:end]. 371 // The start index is inclusive and the end index is exclusive. 372 type span struct { 373 start int 374 end int 375 } 376 spans := make([]span, 0, 32) 377 378 // Find the field start and end indices. 379 wasField := false 380 fromIndex := 0 381 for i, rune := range s { 382 if f(rune) { 383 if wasField { 384 spans = append(spans, span{start: fromIndex, end: i}) 385 wasField = false 386 } 387 } else { 388 if !wasField { 389 fromIndex = i 390 wasField = true 391 } 392 } 393 } 394 395 // Last field might end at EOF. 396 if wasField { 397 spans = append(spans, span{fromIndex, len(s)}) 398 } 399 400 // Create strings from recorded field indices. 401 a := make([]string, len(spans)) 402 for i, span := range spans { 403 a[i] = s[span.start:span.end] 404 } 405 406 return a 407 } 408 409 // Join concatenates the elements of a to create a single string. The separator string 410 // sep is placed between elements in the resulting string. 411 func Join(a []string, sep string) string { 412 switch len(a) { 413 case 0: 414 return "" 415 case 1: 416 return a[0] 417 case 2: 418 // Special case for common small values. 419 // Remove if golang.org/issue/6714 is fixed 420 return a[0] + sep + a[1] 421 case 3: 422 // Special case for common small values. 423 // Remove if golang.org/issue/6714 is fixed 424 return a[0] + sep + a[1] + sep + a[2] 425 } 426 n := len(sep) * (len(a) - 1) 427 for i := 0; i < len(a); i++ { 428 n += len(a[i]) 429 } 430 431 b := make([]byte, n) 432 bp := copy(b, a[0]) 433 for _, s := range a[1:] { 434 bp += copy(b[bp:], sep) 435 bp += copy(b[bp:], s) 436 } 437 return string(b) 438 } 439 440 // HasPrefix tests whether the string s begins with prefix. 441 func HasPrefix(s, prefix string) bool { 442 return len(s) >= len(prefix) && s[0:len(prefix)] == prefix 443 } 444 445 // HasSuffix tests whether the string s ends with suffix. 446 func HasSuffix(s, suffix string) bool { 447 return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix 448 } 449 450 // Map returns a copy of the string s with all its characters modified 451 // according to the mapping function. If mapping returns a negative value, the character is 452 // dropped from the string with no replacement. 453 func Map(mapping func(rune) rune, s string) string { 454 // In the worst case, the string can grow when mapped, making 455 // things unpleasant. But it's so rare we barge in assuming it's 456 // fine. It could also shrink but that falls out naturally. 457 458 // The output buffer b is initialized on demand, the first 459 // time a character differs. 460 var b []byte 461 // nbytes is the number of bytes encoded in b. 462 var nbytes int 463 464 for i, c := range s { 465 r := mapping(c) 466 if r == c { 467 continue 468 } 469 470 b = make([]byte, len(s)+utf8.UTFMax) 471 nbytes = copy(b, s[:i]) 472 if r >= 0 { 473 if r <= utf8.RuneSelf { 474 b[nbytes] = byte(r) 475 nbytes++ 476 } else { 477 nbytes += utf8.EncodeRune(b[nbytes:], r) 478 } 479 } 480 481 if c == utf8.RuneError { 482 // RuneError is the result of either decoding 483 // an invalid sequence or '\uFFFD'. Determine 484 // the correct number of bytes we need to advance. 485 _, w := utf8.DecodeRuneInString(s[i:]) 486 i += w 487 } else { 488 i += utf8.RuneLen(c) 489 } 490 491 s = s[i:] 492 break 493 } 494 495 if b == nil { 496 return s 497 } 498 499 for _, c := range s { 500 r := mapping(c) 501 502 // common case 503 if (0 <= r && r <= utf8.RuneSelf) && nbytes < len(b) { 504 b[nbytes] = byte(r) 505 nbytes++ 506 continue 507 } 508 509 // b is not big enough or r is not a ASCII rune. 510 if r >= 0 { 511 if nbytes+utf8.UTFMax >= len(b) { 512 // Grow the buffer. 513 nb := make([]byte, 2*len(b)) 514 copy(nb, b[:nbytes]) 515 b = nb 516 } 517 nbytes += utf8.EncodeRune(b[nbytes:], r) 518 } 519 } 520 521 return string(b[:nbytes]) 522 } 523 524 // Repeat returns a new string consisting of count copies of the string s. 525 // 526 // It panics if count is negative or if 527 // the result of (len(s) * count) overflows. 528 func Repeat(s string, count int) string { 529 // Since we cannot return an error on overflow, 530 // we should panic if the repeat will generate 531 // an overflow. 532 // See Issue golang.org/issue/16237 533 if count < 0 { 534 panic("strings: negative Repeat count") 535 } else if count > 0 && len(s)*count/count != len(s) { 536 panic("strings: Repeat count causes overflow") 537 } 538 539 b := make([]byte, len(s)*count) 540 bp := copy(b, s) 541 for bp < len(b) { 542 copy(b[bp:], b[:bp]) 543 bp *= 2 544 } 545 return string(b) 546 } 547 548 // ToUpper returns a copy of the string s with all Unicode letters mapped to their upper case. 549 func ToUpper(s string) string { return Map(unicode.ToUpper, s) } 550 551 // ToLower returns a copy of the string s with all Unicode letters mapped to their lower case. 552 func ToLower(s string) string { return Map(unicode.ToLower, s) } 553 554 // ToTitle returns a copy of the string s with all Unicode letters mapped to their title case. 555 func ToTitle(s string) string { return Map(unicode.ToTitle, s) } 556 557 // ToUpperSpecial returns a copy of the string s with all Unicode letters mapped to their 558 // upper case, giving priority to the special casing rules. 559 func ToUpperSpecial(c unicode.SpecialCase, s string) string { 560 return Map(func(r rune) rune { return c.ToUpper(r) }, s) 561 } 562 563 // ToLowerSpecial returns a copy of the string s with all Unicode letters mapped to their 564 // lower case, giving priority to the special casing rules. 565 func ToLowerSpecial(c unicode.SpecialCase, s string) string { 566 return Map(func(r rune) rune { return c.ToLower(r) }, s) 567 } 568 569 // ToTitleSpecial returns a copy of the string s with all Unicode letters mapped to their 570 // title case, giving priority to the special casing rules. 571 func ToTitleSpecial(c unicode.SpecialCase, s string) string { 572 return Map(func(r rune) rune { return c.ToTitle(r) }, s) 573 } 574 575 // isSeparator reports whether the rune could mark a word boundary. 576 // TODO: update when package unicode captures more of the properties. 577 func isSeparator(r rune) bool { 578 // ASCII alphanumerics and underscore are not separators 579 if r <= 0x7F { 580 switch { 581 case '0' <= r && r <= '9': 582 return false 583 case 'a' <= r && r <= 'z': 584 return false 585 case 'A' <= r && r <= 'Z': 586 return false 587 case r == '_': 588 return false 589 } 590 return true 591 } 592 // Letters and digits are not separators 593 if unicode.IsLetter(r) || unicode.IsDigit(r) { 594 return false 595 } 596 // Otherwise, all we can do for now is treat spaces as separators. 597 return unicode.IsSpace(r) 598 } 599 600 // Title returns a copy of the string s with all Unicode letters that begin words 601 // mapped to their title case. 602 // 603 // BUG(rsc): The rule Title uses for word boundaries does not handle Unicode punctuation properly. 604 func Title(s string) string { 605 // Use a closure here to remember state. 606 // Hackish but effective. Depends on Map scanning in order and calling 607 // the closure once per rune. 608 prev := ' ' 609 return Map( 610 func(r rune) rune { 611 if isSeparator(prev) { 612 prev = r 613 return unicode.ToTitle(r) 614 } 615 prev = r 616 return r 617 }, 618 s) 619 } 620 621 // TrimLeftFunc returns a slice of the string s with all leading 622 // Unicode code points c satisfying f(c) removed. 623 func TrimLeftFunc(s string, f func(rune) bool) string { 624 i := indexFunc(s, f, false) 625 if i == -1 { 626 return "" 627 } 628 return s[i:] 629 } 630 631 // TrimRightFunc returns a slice of the string s with all trailing 632 // Unicode code points c satisfying f(c) removed. 633 func TrimRightFunc(s string, f func(rune) bool) string { 634 i := lastIndexFunc(s, f, false) 635 if i >= 0 && s[i] >= utf8.RuneSelf { 636 _, wid := utf8.DecodeRuneInString(s[i:]) 637 i += wid 638 } else { 639 i++ 640 } 641 return s[0:i] 642 } 643 644 // TrimFunc returns a slice of the string s with all leading 645 // and trailing Unicode code points c satisfying f(c) removed. 646 func TrimFunc(s string, f func(rune) bool) string { 647 return TrimRightFunc(TrimLeftFunc(s, f), f) 648 } 649 650 // IndexFunc returns the index into s of the first Unicode 651 // code point satisfying f(c), or -1 if none do. 652 func IndexFunc(s string, f func(rune) bool) int { 653 return indexFunc(s, f, true) 654 } 655 656 // LastIndexFunc returns the index into s of the last 657 // Unicode code point satisfying f(c), or -1 if none do. 658 func LastIndexFunc(s string, f func(rune) bool) int { 659 return lastIndexFunc(s, f, true) 660 } 661 662 // indexFunc is the same as IndexFunc except that if 663 // truth==false, the sense of the predicate function is 664 // inverted. 665 func indexFunc(s string, f func(rune) bool, truth bool) int { 666 for i, r := range s { 667 if f(r) == truth { 668 return i 669 } 670 } 671 return -1 672 } 673 674 // lastIndexFunc is the same as LastIndexFunc except that if 675 // truth==false, the sense of the predicate function is 676 // inverted. 677 func lastIndexFunc(s string, f func(rune) bool, truth bool) int { 678 for i := len(s); i > 0; { 679 r, size := utf8.DecodeLastRuneInString(s[0:i]) 680 i -= size 681 if f(r) == truth { 682 return i 683 } 684 } 685 return -1 686 } 687 688 // asciiSet is a 32-byte value, where each bit represents the presence of a 689 // given ASCII character in the set. The 128-bits of the lower 16 bytes, 690 // starting with the least-significant bit of the lowest word to the 691 // most-significant bit of the highest word, map to the full range of all 692 // 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed, 693 // ensuring that any non-ASCII character will be reported as not in the set. 694 type asciiSet [8]uint32 695 696 // makeASCIISet creates a set of ASCII characters and reports whether all 697 // characters in chars are ASCII. 698 func makeASCIISet(chars string) (as asciiSet, ok bool) { 699 for i := 0; i < len(chars); i++ { 700 c := chars[i] 701 if c >= utf8.RuneSelf { 702 return as, false 703 } 704 as[c>>5] |= 1 << uint(c&31) 705 } 706 return as, true 707 } 708 709 // contains reports whether c is inside the set. 710 func (as *asciiSet) contains(c byte) bool { 711 return (as[c>>5] & (1 << uint(c&31))) != 0 712 } 713 714 func makeCutsetFunc(cutset string) func(rune) bool { 715 if len(cutset) == 1 && cutset[0] < utf8.RuneSelf { 716 return func(r rune) bool { 717 return r == rune(cutset[0]) 718 } 719 } 720 if as, isASCII := makeASCIISet(cutset); isASCII { 721 return func(r rune) bool { 722 return r < utf8.RuneSelf && as.contains(byte(r)) 723 } 724 } 725 return func(r rune) bool { return IndexRune(cutset, r) >= 0 } 726 } 727 728 // Trim returns a slice of the string s with all leading and 729 // trailing Unicode code points contained in cutset removed. 730 func Trim(s string, cutset string) string { 731 if s == "" || cutset == "" { 732 return s 733 } 734 return TrimFunc(s, makeCutsetFunc(cutset)) 735 } 736 737 // TrimLeft returns a slice of the string s with all leading 738 // Unicode code points contained in cutset removed. 739 func TrimLeft(s string, cutset string) string { 740 if s == "" || cutset == "" { 741 return s 742 } 743 return TrimLeftFunc(s, makeCutsetFunc(cutset)) 744 } 745 746 // TrimRight returns a slice of the string s, with all trailing 747 // Unicode code points contained in cutset removed. 748 func TrimRight(s string, cutset string) string { 749 if s == "" || cutset == "" { 750 return s 751 } 752 return TrimRightFunc(s, makeCutsetFunc(cutset)) 753 } 754 755 // TrimSpace returns a slice of the string s, with all leading 756 // and trailing white space removed, as defined by Unicode. 757 func TrimSpace(s string) string { 758 return TrimFunc(s, unicode.IsSpace) 759 } 760 761 // TrimPrefix returns s without the provided leading prefix string. 762 // If s doesn't start with prefix, s is returned unchanged. 763 func TrimPrefix(s, prefix string) string { 764 if HasPrefix(s, prefix) { 765 return s[len(prefix):] 766 } 767 return s 768 } 769 770 // TrimSuffix returns s without the provided trailing suffix string. 771 // If s doesn't end with suffix, s is returned unchanged. 772 func TrimSuffix(s, suffix string) string { 773 if HasSuffix(s, suffix) { 774 return s[:len(s)-len(suffix)] 775 } 776 return s 777 } 778 779 // Replace returns a copy of the string s with the first n 780 // non-overlapping instances of old replaced by new. 781 // If old is empty, it matches at the beginning of the string 782 // and after each UTF-8 sequence, yielding up to k+1 replacements 783 // for a k-rune string. 784 // If n < 0, there is no limit on the number of replacements. 785 func Replace(s, old, new string, n int) string { 786 if old == new || n == 0 { 787 return s // avoid allocation 788 } 789 790 // Compute number of replacements. 791 if m := Count(s, old); m == 0 { 792 return s // avoid allocation 793 } else if n < 0 || m < n { 794 n = m 795 } 796 797 // Apply replacements to buffer. 798 t := make([]byte, len(s)+n*(len(new)-len(old))) 799 w := 0 800 start := 0 801 for i := 0; i < n; i++ { 802 j := start 803 if len(old) == 0 { 804 if i > 0 { 805 _, wid := utf8.DecodeRuneInString(s[start:]) 806 j += wid 807 } 808 } else { 809 j += Index(s[start:], old) 810 } 811 w += copy(t[w:], s[start:j]) 812 w += copy(t[w:], new) 813 start = j + len(old) 814 } 815 w += copy(t[w:], s[start:]) 816 return string(t[0:w]) 817 } 818 819 // EqualFold reports whether s and t, interpreted as UTF-8 strings, 820 // are equal under Unicode case-folding. 821 func EqualFold(s, t string) bool { 822 for s != "" && t != "" { 823 // Extract first rune from each string. 824 var sr, tr rune 825 if s[0] < utf8.RuneSelf { 826 sr, s = rune(s[0]), s[1:] 827 } else { 828 r, size := utf8.DecodeRuneInString(s) 829 sr, s = r, s[size:] 830 } 831 if t[0] < utf8.RuneSelf { 832 tr, t = rune(t[0]), t[1:] 833 } else { 834 r, size := utf8.DecodeRuneInString(t) 835 tr, t = r, t[size:] 836 } 837 838 // If they match, keep going; if not, return false. 839 840 // Easy case. 841 if tr == sr { 842 continue 843 } 844 845 // Make sr < tr to simplify what follows. 846 if tr < sr { 847 tr, sr = sr, tr 848 } 849 // Fast check for ASCII. 850 if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' { 851 // ASCII, and sr is upper case. tr must be lower case. 852 if tr == sr+'a'-'A' { 853 continue 854 } 855 return false 856 } 857 858 // General case. SimpleFold(x) returns the next equivalent rune > x 859 // or wraps around to smaller values. 860 r := unicode.SimpleFold(sr) 861 for r != sr && r < tr { 862 r = unicode.SimpleFold(r) 863 } 864 if r == tr { 865 continue 866 } 867 return false 868 } 869 870 // One string is empty. Are both? 871 return s == t 872 }