1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Unicode string slices
13 //! *[See also the `str` primitive type](../primitive.str.html).*
16 #![stable(feature = "rust1", since = "1.0.0")]
18 // Many of the usings in this module are only used in the test configuration.
19 // It's cleaner to just turn off the unused_imports warning than to fix them.
20 #![allow(unused_imports)]
22 use core::str as core_str;
23 use core::str::pattern::Pattern;
24 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
26 use rustc_unicode::str::{UnicodeStr, Utf16Encoder};
28 use vec_deque::VecDeque;
29 use borrow::{Borrow, ToOwned};
33 use slice::SliceConcatExt;
36 #[stable(feature = "rust1", since = "1.0.0")]
37 pub use core::str::{FromStr, Utf8Error};
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub use core::str::{Lines, LinesAny, CharRange};
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub use core::str::{Split, RSplit};
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub use core::str::{SplitN, RSplitN};
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub use core::str::{SplitTerminator, RSplitTerminator};
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub use core::str::{Matches, RMatches};
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub use core::str::{MatchIndices, RMatchIndices};
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub use core::str::{from_utf8_unchecked, ParseBoolError};
55 #[stable(feature = "rust1", since = "1.0.0")]
56 pub use rustc_unicode::str::SplitWhitespace;
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub use core::str::pattern;
60 #[unstable(feature = "slice_concat_ext",
61 reason = "trait should not have to exist",
63 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
66 fn concat(&self) -> String {
71 // `len` calculation may overflow but push_str will check boundaries
72 let len = self.iter().map(|s| s.borrow().len()).sum();
73 let mut result = String::with_capacity(len);
76 result.push_str(s.borrow())
82 fn join(&self, sep: &str) -> String {
92 // this is wrong without the guarantee that `self` is non-empty
93 // `len` calculation may overflow but push_str but will check boundaries
94 let len = sep.len() * (self.len() - 1) +
95 self.iter().map(|s| s.borrow().len()).sum::<usize>();
96 let mut result = String::with_capacity(len);
103 result.push_str(sep);
105 result.push_str(s.borrow());
110 fn connect(&self, sep: &str) -> String {
115 /// External iterator for a string's UTF-16 code units.
117 /// For use with the `std::iter` module.
119 #[unstable(feature = "str_utf16", issue = "27714")]
120 pub struct Utf16Units<'a> {
121 encoder: Utf16Encoder<Chars<'a>>,
124 #[stable(feature = "rust1", since = "1.0.0")]
125 impl<'a> Iterator for Utf16Units<'a> {
129 fn next(&mut self) -> Option<u16> {
134 fn size_hint(&self) -> (usize, Option<usize>) {
135 self.encoder.size_hint()
139 // Return the initial codepoint accumulator for the first byte.
140 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
141 // for width 3, and 3 bits for width 4
142 macro_rules! utf8_first_byte {
143 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
146 // return the value of $ch updated with continuation byte $byte
147 macro_rules! utf8_acc_cont_byte {
148 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
151 #[stable(feature = "rust1", since = "1.0.0")]
152 impl Borrow<str> for String {
154 fn borrow(&self) -> &str {
159 #[stable(feature = "rust1", since = "1.0.0")]
160 impl ToOwned for str {
162 fn to_owned(&self) -> String {
163 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
167 /// Methods for string slices.
171 /// Returns the length of `self`.
173 /// This length is in bytes, not [`char`]s or graphemes. In other words,
174 /// it may not be what a human considers the length of the string.
176 /// [`char`]: primitive.char.html
183 /// let len = "foo".len();
184 /// assert_eq!(3, len);
186 /// let len = "ƒoo".len(); // fancy f!
187 /// assert_eq!(4, len);
189 #[stable(feature = "rust1", since = "1.0.0")]
191 pub fn len(&self) -> usize {
192 core_str::StrExt::len(self)
195 /// Returns true if this slice has a length of zero bytes.
203 /// assert!(s.is_empty());
205 /// let s = "not empty";
206 /// assert!(!s.is_empty());
209 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn is_empty(&self) -> bool {
211 core_str::StrExt::is_empty(self)
214 /// Checks that `index`-th byte lies at the start and/or end of a
215 /// UTF-8 code point sequence.
217 /// The start and end of the string (when `index == self.len()`) are
221 /// Returns `false` if `index` is greater than `self.len()`.
226 /// #![feature(str_char)]
228 /// let s = "Löwe 老虎 Léopard";
229 /// assert!(s.is_char_boundary(0));
231 /// assert!(s.is_char_boundary(6));
232 /// assert!(s.is_char_boundary(s.len()));
234 /// // second byte of `ö`
235 /// assert!(!s.is_char_boundary(2));
237 /// // third byte of `老`
238 /// assert!(!s.is_char_boundary(8));
240 #[unstable(feature = "str_char",
241 reason = "it is unclear whether this method pulls its weight \
242 with the existence of the char_indices iterator or \
243 this method may want to be replaced with checked \
247 pub fn is_char_boundary(&self, index: usize) -> bool {
248 core_str::StrExt::is_char_boundary(self, index)
251 /// Converts a string slice to a byte slice.
258 /// let bytes = "bors".as_bytes();
259 /// assert_eq!(b"bors", bytes);
261 #[stable(feature = "rust1", since = "1.0.0")]
263 pub fn as_bytes(&self) -> &[u8] {
264 core_str::StrExt::as_bytes(self)
267 /// Converts a string slice to a raw pointer.
269 /// As string slices are a slice of bytes, the raw pointer points to a
270 /// `u8`. This pointer will be pointing to the first byte of the string
279 /// let ptr = s.as_ptr();
281 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn as_ptr(&self) -> *const u8 {
284 core_str::StrExt::as_ptr(self)
287 /// Creates a string slice from another string slice, bypassing safety
290 /// This new slice goes from `begin` to `end`, including `begin` but
293 /// To get a mutable string slice instead, see the
294 /// [`slice_mut_unchecked()`] method.
296 /// [`slice_mut_unchecked()`]: #method.slice_mut_unchecked
300 /// Callers of this function are responsible that three preconditions are
303 /// * `begin` must come before `end`.
304 /// * `begin` and `end` must be byte positions within the string slice.
305 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
312 /// let s = "Löwe 老虎 Léopard";
315 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
318 /// let s = "Hello, world!";
321 /// assert_eq!("world", s.slice_unchecked(7, 12));
324 #[stable(feature = "rust1", since = "1.0.0")]
326 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
327 core_str::StrExt::slice_unchecked(self, begin, end)
330 /// Creates a string slice from another string slice, bypassing safety
333 /// This new slice goes from `begin` to `end`, including `begin` but
336 /// To get an immutable string slice instead, see the
337 /// [`slice_unchecked()`] method.
339 /// [`slice_unchecked()`]: #method.slice_unchecked
343 /// Callers of this function are responsible that three preconditions are
346 /// * `begin` must come before `end`.
347 /// * `begin` and `end` must be byte positions within the string slice.
348 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
349 #[stable(feature = "str_slice_mut", since = "1.5.0")]
351 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
352 core_str::StrExt::slice_mut_unchecked(self, begin, end)
355 /// Given a byte position, returns the next `char` and its index.
359 /// If `i` is greater than or equal to the length of the string.
360 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
364 /// This example manually iterates through the code points of a string;
365 /// this should normally be
366 /// done by `.chars()` or `.char_indices()`.
369 /// #![feature(str_char)]
371 /// use std::str::CharRange;
373 /// let s = "中华Việt Nam";
375 /// while i < s.len() {
376 /// let CharRange {ch, next} = s.char_range_at(i);
377 /// println!("{}: {}", i, ch);
398 #[unstable(feature = "str_char",
399 reason = "often replaced by char_indices, this method may \
400 be removed in favor of just char_at() or eventually \
404 pub fn char_range_at(&self, start: usize) -> CharRange {
405 core_str::StrExt::char_range_at(self, start)
408 /// Given a byte position, returns the previous `char` and its position.
410 /// Note that Unicode has many features, such as combining marks, ligatures,
411 /// and direction marks, that need to be taken into account to correctly reverse a string.
413 /// Returns 0 for next index if called on start index 0.
417 /// If `i` is greater than the length of the string.
418 /// If `i` is not an index following a valid UTF-8 sequence.
422 /// This example manually iterates through the code points of a string;
423 /// this should normally be
424 /// done by `.chars().rev()` or `.char_indices()`.
427 /// #![feature(str_char)]
429 /// use std::str::CharRange;
431 /// let s = "中华Việt Nam";
432 /// let mut i = s.len();
434 /// let CharRange {ch, next} = s.char_range_at_reverse(i);
435 /// println!("{}: {}", i, ch);
456 #[unstable(feature = "str_char",
457 reason = "often replaced by char_indices, this method may \
458 be removed in favor of just char_at_reverse() or \
459 eventually removed altogether",
462 pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
463 core_str::StrExt::char_range_at_reverse(self, start)
466 /// Given a byte position, returns the `char` at that position.
470 /// If `i` is greater than or equal to the length of the string.
471 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
476 /// #![feature(str_char)]
479 /// assert_eq!(s.char_at(1), 'b');
480 /// assert_eq!(s.char_at(2), 'π');
481 /// assert_eq!(s.char_at(4), 'c');
483 #[unstable(feature = "str_char",
484 reason = "frequently replaced by the chars() iterator, this \
485 method may be removed or possibly renamed in the \
486 future; it is normally replaced by chars/char_indices \
487 iterators or by getting the first char from a \
491 pub fn char_at(&self, i: usize) -> char {
492 core_str::StrExt::char_at(self, i)
495 /// Given a byte position, returns the `char` at that position, counting
500 /// If `i` is greater than the length of the string.
501 /// If `i` is not an index following a valid UTF-8 sequence.
506 /// #![feature(str_char)]
509 /// assert_eq!(s.char_at_reverse(1), 'a');
510 /// assert_eq!(s.char_at_reverse(2), 'b');
511 /// assert_eq!(s.char_at_reverse(3), 'π');
513 #[unstable(feature = "str_char",
514 reason = "see char_at for more details, but reverse semantics \
515 are also somewhat unclear, especially with which \
516 cases generate panics",
519 pub fn char_at_reverse(&self, i: usize) -> char {
520 core_str::StrExt::char_at_reverse(self, i)
523 /// Retrieves the first `char` from a `&str` and returns it.
525 /// Note that a single Unicode character (grapheme cluster)
526 /// can be composed of multiple `char`s.
528 /// This does not allocate a new string; instead, it returns a slice that
529 /// points one code point beyond the code point that was shifted.
531 /// `None` is returned if the slice is empty.
536 /// #![feature(str_char)]
538 /// let s = "Łódź"; // \u{141}o\u{301}dz\u{301}
539 /// let (c, s1) = s.slice_shift_char().unwrap();
541 /// assert_eq!(c, 'Ł');
542 /// assert_eq!(s1, "ódź");
544 /// let (c, s2) = s1.slice_shift_char().unwrap();
546 /// assert_eq!(c, 'o');
547 /// assert_eq!(s2, "\u{301}dz\u{301}");
549 #[unstable(feature = "str_char",
550 reason = "awaiting conventions about shifting and slices and \
551 may not be warranted with the existence of the chars \
552 and/or char_indices iterators",
555 pub fn slice_shift_char(&self) -> Option<(char, &str)> {
556 core_str::StrExt::slice_shift_char(self)
559 /// Divide one string slice into two at an index.
561 /// The argument, `mid`, should be a byte offset from the start of the
562 /// string. It must also be on the boundary of a UTF-8 code point.
564 /// The two slices returned go from the start of the string slice to `mid`,
565 /// and from `mid` to the end of the string slice.
567 /// To get mutable string slices instead, see the [`split_at_mut()`]
570 /// [`split_at_mut()`]: #method.split_at_mut
574 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
575 /// beyond the last code point of the string slice.
582 /// let s = "Per Martin-Löf";
584 /// let (first, last) = s.split_at(3);
586 /// assert_eq!("Per", first);
587 /// assert_eq!(" Martin-Löf", last);
590 #[stable(feature = "str_split_at", since = "1.4.0")]
591 pub fn split_at(&self, mid: usize) -> (&str, &str) {
592 core_str::StrExt::split_at(self, mid)
595 /// Divide one mutable string slice into two at an index.
597 /// The argument, `mid`, should be a byte offset from the start of the
598 /// string. It must also be on the boundary of a UTF-8 code point.
600 /// The two slices returned go from the start of the string slice to `mid`,
601 /// and from `mid` to the end of the string slice.
603 /// To get immutable string slices instead, see the [`split_at()`] method.
605 /// [`split_at()`]: #method.split_at
609 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
610 /// beyond the last code point of the string slice.
617 /// let s = "Per Martin-Löf";
619 /// let (first, last) = s.split_at(3);
621 /// assert_eq!("Per", first);
622 /// assert_eq!(" Martin-Löf", last);
625 #[stable(feature = "str_split_at", since = "1.4.0")]
626 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
627 core_str::StrExt::split_at_mut(self, mid)
630 /// Returns an iterator over the `char`s of a string slice.
632 /// As a string slice consists of valid UTF-8, we can iterate through a
633 /// string slice by [`char`]. This method returns such an iterator.
635 /// It's important to remember that [`char`] represents a Unicode Scalar
636 /// Value, and may not match your idea of what a 'character' is. Iteration
637 /// over grapheme clusters may be what you actually want.
639 /// [`char`]: primitive.char.html
646 /// let word = "goodbye";
648 /// let count = word.chars().count();
649 /// assert_eq!(7, count);
651 /// let mut chars = word.chars();
653 /// assert_eq!(Some('g'), chars.next());
654 /// assert_eq!(Some('o'), chars.next());
655 /// assert_eq!(Some('o'), chars.next());
656 /// assert_eq!(Some('d'), chars.next());
657 /// assert_eq!(Some('b'), chars.next());
658 /// assert_eq!(Some('y'), chars.next());
659 /// assert_eq!(Some('e'), chars.next());
661 /// assert_eq!(None, chars.next());
664 /// Remember, `char`s may not match your human intuition about characters:
669 /// let mut chars = y.chars();
671 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
672 /// assert_eq!(Some('\u{0306}'), chars.next());
674 /// assert_eq!(None, chars.next());
676 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn chars(&self) -> Chars {
679 core_str::StrExt::chars(self)
681 /// Returns an iterator over the `char`s of a string slice, and their
684 /// As a string slice consists of valid UTF-8, we can iterate through a
685 /// string slice by `char`. This method returns an iterator of both
686 /// these `char`s, as well as their byte positions.
688 /// The iterator yields tuples. The position is first, the `char` is
696 /// let word = "goodbye";
698 /// let count = word.char_indices().count();
699 /// assert_eq!(7, count);
701 /// let mut char_indices = word.char_indices();
703 /// assert_eq!(Some((0, 'g')), char_indices.next());
704 /// assert_eq!(Some((1, 'o')), char_indices.next());
705 /// assert_eq!(Some((2, 'o')), char_indices.next());
706 /// assert_eq!(Some((3, 'd')), char_indices.next());
707 /// assert_eq!(Some((4, 'b')), char_indices.next());
708 /// assert_eq!(Some((5, 'y')), char_indices.next());
709 /// assert_eq!(Some((6, 'e')), char_indices.next());
711 /// assert_eq!(None, char_indices.next());
714 /// Remember, `char`s may not match your human intuition about characters:
719 /// let mut char_indices = y.char_indices();
721 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
722 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
724 /// assert_eq!(None, char_indices.next());
726 #[stable(feature = "rust1", since = "1.0.0")]
728 pub fn char_indices(&self) -> CharIndices {
729 core_str::StrExt::char_indices(self)
732 /// An iterator over the bytes of a string slice.
734 /// As a string slice consists of a sequence of bytes, we can iterate
735 /// through a string slice by byte. This method returns such an iterator.
742 /// let mut bytes = "bors".bytes();
744 /// assert_eq!(Some(b'b'), bytes.next());
745 /// assert_eq!(Some(b'o'), bytes.next());
746 /// assert_eq!(Some(b'r'), bytes.next());
747 /// assert_eq!(Some(b's'), bytes.next());
749 /// assert_eq!(None, bytes.next());
751 #[stable(feature = "rust1", since = "1.0.0")]
753 pub fn bytes(&self) -> Bytes {
754 core_str::StrExt::bytes(self)
757 /// Split a string slice by whitespace.
759 /// The iterator returned will return string slices that are sub-slices of
760 /// the original string slice, separated by any amount of whitespace.
762 /// 'Whitespace' is defined according to the terms of the Unicode Derived
763 /// Core Property `White_Space`.
770 /// let mut iter = "A few words".split_whitespace();
772 /// assert_eq!(Some("A"), iter.next());
773 /// assert_eq!(Some("few"), iter.next());
774 /// assert_eq!(Some("words"), iter.next());
776 /// assert_eq!(None, iter.next());
779 /// All kinds of whitespace are considered:
782 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
783 /// assert_eq!(Some("Mary"), iter.next());
784 /// assert_eq!(Some("had"), iter.next());
785 /// assert_eq!(Some("a"), iter.next());
786 /// assert_eq!(Some("little"), iter.next());
787 /// assert_eq!(Some("lamb"), iter.next());
789 /// assert_eq!(None, iter.next());
791 #[stable(feature = "split_whitespace", since = "1.1.0")]
793 pub fn split_whitespace(&self) -> SplitWhitespace {
794 UnicodeStr::split_whitespace(self)
797 /// An iterator over the lines of a string, as string slices.
799 /// Lines are ended with either a newline (`\n`) or a carriage return with
800 /// a line feed (`\r\n`).
802 /// The final line ending is optional.
809 /// let text = "foo\r\nbar\n\nbaz\n";
810 /// let mut lines = text.lines();
812 /// assert_eq!(Some("foo"), lines.next());
813 /// assert_eq!(Some("bar"), lines.next());
814 /// assert_eq!(Some(""), lines.next());
815 /// assert_eq!(Some("baz"), lines.next());
817 /// assert_eq!(None, lines.next());
820 /// The final line ending isn't required:
823 /// let text = "foo\nbar\n\r\nbaz";
824 /// let mut lines = text.lines();
826 /// assert_eq!(Some("foo"), lines.next());
827 /// assert_eq!(Some("bar"), lines.next());
828 /// assert_eq!(Some(""), lines.next());
829 /// assert_eq!(Some("baz"), lines.next());
831 /// assert_eq!(None, lines.next());
833 #[stable(feature = "rust1", since = "1.0.0")]
835 pub fn lines(&self) -> Lines {
836 core_str::StrExt::lines(self)
839 /// An iterator over the lines of a string.
840 #[stable(feature = "rust1", since = "1.0.0")]
841 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
844 pub fn lines_any(&self) -> LinesAny {
845 core_str::StrExt::lines_any(self)
848 /// Returns an iterator of `u16` over the string encoded as UTF-16.
849 #[unstable(feature = "str_utf16",
850 reason = "this functionality may only be provided by libunicode",
852 pub fn utf16_units(&self) -> Utf16Units {
853 Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
856 /// Returns `true` if the given pattern matches a sub-slice of
857 /// this string slice.
859 /// Returns `false` if it does not.
866 /// let bananas = "bananas";
868 /// assert!(bananas.contains("nana"));
869 /// assert!(!bananas.contains("apples"));
871 #[stable(feature = "rust1", since = "1.0.0")]
872 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
873 core_str::StrExt::contains(self, pat)
876 /// Returns `true` if the given pattern matches a prefix of this
879 /// Returns `false` if it does not.
886 /// let bananas = "bananas";
888 /// assert!(bananas.starts_with("bana"));
889 /// assert!(!bananas.starts_with("nana"));
891 #[stable(feature = "rust1", since = "1.0.0")]
892 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
893 core_str::StrExt::starts_with(self, pat)
896 /// Returns `true` if the given pattern matches a suffix of this
899 /// Returns `false` if it does not.
906 /// let bananas = "bananas";
908 /// assert!(bananas.ends_with("anas"));
909 /// assert!(!bananas.ends_with("nana"));
911 #[stable(feature = "rust1", since = "1.0.0")]
912 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
913 where P::Searcher: ReverseSearcher<'a>
915 core_str::StrExt::ends_with(self, pat)
918 /// Returns the byte index of the first character of this string slice that
919 /// matches the pattern.
921 /// Returns `None` if the pattern doesn't match.
923 /// The pattern can be a `&str`, [`char`], or a closure that determines if
924 /// a character matches.
926 /// [`char`]: primitive.char.html
933 /// let s = "Löwe 老虎 Léopard";
935 /// assert_eq!(s.find('L'), Some(0));
936 /// assert_eq!(s.find('é'), Some(14));
937 /// assert_eq!(s.find("Léopard"), Some(13));
940 /// More complex patterns with closures:
943 /// let s = "Löwe 老虎 Léopard";
945 /// assert_eq!(s.find(char::is_whitespace), Some(5));
946 /// assert_eq!(s.find(char::is_lowercase), Some(1));
949 /// Not finding the pattern:
952 /// let s = "Löwe 老虎 Léopard";
953 /// let x: &[_] = &['1', '2'];
955 /// assert_eq!(s.find(x), None);
957 #[stable(feature = "rust1", since = "1.0.0")]
958 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
959 core_str::StrExt::find(self, pat)
962 /// Returns the byte index of the last character of this string slice that
963 /// matches the pattern.
965 /// Returns `None` if the pattern doesn't match.
967 /// The pattern can be a `&str`, [`char`], or a closure that determines if
968 /// a character matches.
970 /// [`char`]: primitive.char.html
977 /// let s = "Löwe 老虎 Léopard";
979 /// assert_eq!(s.rfind('L'), Some(13));
980 /// assert_eq!(s.rfind('é'), Some(14));
983 /// More complex patterns with closures:
986 /// let s = "Löwe 老虎 Léopard";
988 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
989 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
992 /// Not finding the pattern:
995 /// let s = "Löwe 老虎 Léopard";
996 /// let x: &[_] = &['1', '2'];
998 /// assert_eq!(s.rfind(x), None);
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1002 where P::Searcher: ReverseSearcher<'a>
1004 core_str::StrExt::rfind(self, pat)
1007 /// An iterator over substrings of this string slice, separated by
1008 /// characters matched by a pattern.
1010 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1013 /// # Iterator behavior
1015 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1016 /// allows a reverse search and forward/reverse search yields the same
1017 /// elements. This is true for, eg, [`char`] but not for `&str`.
1019 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1021 /// If the pattern allows a reverse search but its results might differ
1022 /// from a forward search, the [`rsplit()`] method can be used.
1024 /// [`char`]: primitive.char.html
1025 /// [`rsplit()`]: #method.rsplit
1029 /// Simple patterns:
1032 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1033 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1035 /// let v: Vec<&str> = "".split('X').collect();
1036 /// assert_eq!(v, [""]);
1038 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1039 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1041 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1042 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1044 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1045 /// assert_eq!(v, ["abc", "def", "ghi"]);
1047 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1048 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1051 /// A more complex pattern, using a closure:
1054 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1055 /// assert_eq!(v, ["abc", "def", "ghi"]);
1058 /// If a string contains multiple contiguous separators, you will end up
1059 /// with empty strings in the output:
1062 /// let x = "||||a||b|c".to_string();
1063 /// let d: Vec<_> = x.split('|').collect();
1065 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1068 /// This can lead to possibly surprising behavior when whitespace is used
1069 /// as the separator. This code is correct:
1072 /// let x = " a b c".to_string();
1073 /// let d: Vec<_> = x.split(' ').collect();
1075 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1078 /// It does _not_ give you:
1081 /// assert_eq!(d, &["a", "b", "c"]);
1084 /// Use [`split_whitespace()`] for this behavior.
1086 /// [`split_whitespace()`]: #method.split_whitespace
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1089 core_str::StrExt::split(self, pat)
1092 /// An iterator over substrings of the given string slice, separated by
1093 /// characters matched by a pattern and yielded in reverse order.
1095 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1098 /// [`char`]: primitive.char.html
1100 /// # Iterator behavior
1102 /// The returned iterator requires that the pattern supports a reverse
1103 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1104 /// search yields the same elements.
1106 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1108 /// For iterating from the front, the [`split()`] method can be used.
1110 /// [`split()`]: #method.split
1114 /// Simple patterns:
1117 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1118 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1120 /// let v: Vec<&str> = "".rsplit('X').collect();
1121 /// assert_eq!(v, [""]);
1123 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1124 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1126 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1127 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1130 /// A more complex pattern, using a closure:
1133 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1134 /// assert_eq!(v, ["ghi", "def", "abc"]);
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1138 where P::Searcher: ReverseSearcher<'a>
1140 core_str::StrExt::rsplit(self, pat)
1143 /// An iterator over substrings of the given string slice, separated by
1144 /// characters matched by a pattern.
1146 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1149 /// Equivalent to [`split()`], except that the trailing substring
1150 /// is skipped if empty.
1152 /// [`split()`]: #method.split
1154 /// This method can be used for string data that is _terminated_,
1155 /// rather than _separated_ by a pattern.
1157 /// # Iterator behavior
1159 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1160 /// allows a reverse search and forward/reverse search yields the same
1161 /// elements. This is true for, eg, [`char`] but not for `&str`.
1163 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1164 /// [`char`]: primitive.char.html
1166 /// If the pattern allows a reverse search but its results might differ
1167 /// from a forward search, the [`rsplit_terminator()`] method can be used.
1169 /// [`rsplit_terminator()`]: #method.rsplit_terminator
1176 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1177 /// assert_eq!(v, ["A", "B"]);
1179 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1180 /// assert_eq!(v, ["A", "", "B", ""]);
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1184 core_str::StrExt::split_terminator(self, pat)
1187 /// An iterator over substrings of `self`, separated by characters
1188 /// matched by a pattern and yielded in reverse order.
1190 /// The pattern can be a simple `&str`, `char`, or a closure that
1191 /// determines the split.
1192 /// Additional libraries might provide more complex patterns like
1193 /// regular expressions.
1195 /// Equivalent to `split`, except that the trailing substring is
1196 /// skipped if empty.
1198 /// This method can be used for string data that is _terminated_,
1199 /// rather than _separated_ by a pattern.
1201 /// # Iterator behavior
1203 /// The returned iterator requires that the pattern supports a
1204 /// reverse search, and it will be double ended if a forward/reverse
1205 /// search yields the same elements.
1207 /// For iterating from the front, the [`split_terminator()`] method can be
1210 /// [`split_terminator()`]: #method.split_terminator
1215 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1216 /// assert_eq!(v, ["B", "A"]);
1218 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1219 /// assert_eq!(v, ["", "B", "", "A"]);
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1223 where P::Searcher: ReverseSearcher<'a>
1225 core_str::StrExt::rsplit_terminator(self, pat)
1228 /// An iterator over substrings of the given string slice, separated by a
1229 /// pattern, restricted to returning at most `count` items.
1231 /// The last element returned, if any, will contain the remainder of the
1234 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1237 /// [`char`]: primitive.char.html
1239 /// # Iterator behavior
1241 /// The returned iterator will not be double ended, because it is
1242 /// not efficient to support.
1244 /// If the pattern allows a reverse search, the [`rsplitn()`] method can be
1247 /// [`rsplitn()`]: #method.rsplitn
1251 /// Simple patterns:
1254 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1255 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1257 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1258 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1260 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1261 /// assert_eq!(v, ["abcXdef"]);
1263 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1264 /// assert_eq!(v, [""]);
1267 /// A more complex pattern, using a closure:
1270 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1271 /// assert_eq!(v, ["abc", "defXghi"]);
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 pub fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1275 core_str::StrExt::splitn(self, count, pat)
1278 /// An iterator over substrings of this string slice, separated by a
1279 /// pattern, starting from the end of the string, restricted to returning
1280 /// at most `count` items.
1282 /// The last element returned, if any, will contain the remainder of the
1285 /// The pattern can be a `&str`, [`char`], or a closure that
1286 /// determines the split.
1288 /// [`char`]: primitive.char.html
1290 /// # Iterator behavior
1292 /// The returned iterator will not be double ended, because it is not
1293 /// efficient to support.
1295 /// For splitting from the front, the [`splitn()`] method can be used.
1297 /// [`splitn()`]: #method.splitn
1301 /// Simple patterns:
1304 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1305 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1307 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1308 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1310 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1311 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1314 /// A more complex pattern, using a closure:
1317 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1318 /// assert_eq!(v, ["ghi", "abc1def"]);
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1322 where P::Searcher: ReverseSearcher<'a>
1324 core_str::StrExt::rsplitn(self, count, pat)
1327 /// An iterator over the matches of a pattern within the given string
1330 /// The pattern can be a `&str`, [`char`], or a closure that
1331 /// determines if a character matches.
1333 /// [`char`]: primitive.char.html
1335 /// # Iterator behavior
1337 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1338 /// allows a reverse search and forward/reverse search yields the same
1339 /// elements. This is true for, eg, [`char`] but not for `&str`.
1341 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1342 /// [`char`]: primitive.char.html
1344 /// If the pattern allows a reverse search but its results might differ
1345 /// from a forward search, the [`rmatches()`] method can be used.
1347 /// [`rmatches()`]: #method.rmatches
1354 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1355 /// assert_eq!(v, ["abc", "abc", "abc"]);
1357 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1358 /// assert_eq!(v, ["1", "2", "3"]);
1360 #[stable(feature = "str_matches", since = "1.2.0")]
1361 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1362 core_str::StrExt::matches(self, pat)
1365 /// An iterator over the matches of a pattern within this string slice,
1366 /// yielded in reverse order.
1368 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1369 /// a character matches.
1371 /// [`char`]: primitive.char.html
1373 /// # Iterator behavior
1375 /// The returned iterator requires that the pattern supports a reverse
1376 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1377 /// search yields the same elements.
1379 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1381 /// For iterating from the front, the [`matches()`] method can be used.
1383 /// [`matches()`]: #method.matches
1390 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1391 /// assert_eq!(v, ["abc", "abc", "abc"]);
1393 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1394 /// assert_eq!(v, ["3", "2", "1"]);
1396 #[stable(feature = "str_matches", since = "1.2.0")]
1397 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1398 where P::Searcher: ReverseSearcher<'a>
1400 core_str::StrExt::rmatches(self, pat)
1403 /// An iterator over the disjoint matches of a pattern within this string
1404 /// slice as well as the index that the match starts at.
1406 /// For matches of `pat` within `self` that overlap, only the indices
1407 /// corresponding to the first match are returned.
1409 /// The pattern can be a `&str`, [`char`], or a closure that determines
1410 /// if a character matches.
1412 /// [`char`]: primitive.char.html
1414 /// # Iterator behavior
1416 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1417 /// allows a reverse search and forward/reverse search yields the same
1418 /// elements. This is true for, eg, [`char`] but not for `&str`.
1420 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1422 /// If the pattern allows a reverse search but its results might differ
1423 /// from a forward search, the [`rmatch_indices()`] method can be used.
1425 /// [`rmatch_indices()`]: #method.rmatch_indices
1432 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1433 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1435 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1436 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1438 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1439 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1441 #[stable(feature = "str_match_indices", since = "1.5.0")]
1442 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1443 core_str::StrExt::match_indices(self, pat)
1446 /// An iterator over the disjoint matches of a pattern within `self`,
1447 /// yielded in reverse order along with the index of the match.
1449 /// For matches of `pat` within `self` that overlap, only the indices
1450 /// corresponding to the last match are returned.
1452 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1453 /// character matches.
1455 /// [`char`]: primitive.char.html
1457 /// # Iterator behavior
1459 /// The returned iterator requires that the pattern supports a reverse
1460 /// search, and it will be a `[DoubleEndedIterator]` if a forward/reverse
1461 /// search yields the same elements.
1463 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1465 /// For iterating from the front, the [`match_indices()`] method can be used.
1467 /// [`match_indices()`]: #method.match_indices
1474 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1475 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1477 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1478 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1480 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1481 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1483 #[stable(feature = "str_match_indices", since = "1.5.0")]
1484 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1485 where P::Searcher: ReverseSearcher<'a>
1487 core_str::StrExt::rmatch_indices(self, pat)
1490 /// Returns a string slice with leading and trailing whitespace removed.
1492 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1493 /// Core Property `White_Space`.
1500 /// let s = " Hello\tworld\t";
1502 /// assert_eq!("Hello\tworld", s.trim());
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 pub fn trim(&self) -> &str {
1506 UnicodeStr::trim(self)
1509 /// Returns a string slice with leading whitespace removed.
1511 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1512 /// Core Property `White_Space`.
1519 /// let s = " Hello\tworld\t";
1521 /// assert_eq!("Hello\tworld\t", s.trim_left());
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 pub fn trim_left(&self) -> &str {
1525 UnicodeStr::trim_left(self)
1528 /// Returns a string slice with trailing whitespace removed.
1530 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1531 /// Core Property `White_Space`.
1538 /// let s = " Hello\tworld\t";
1540 /// assert_eq!(" Hello\tworld", s.trim_right());
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 pub fn trim_right(&self) -> &str {
1544 UnicodeStr::trim_right(self)
1547 /// Returns a string slice with all prefixes and suffixes that match a
1548 /// pattern repeatedly removed.
1550 /// The pattern can be a `&str`, [`char`], or a closure that determines
1551 /// if a character matches.
1553 /// [`char`]: primitive.char.html
1557 /// Simple patterns:
1560 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1561 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1563 /// let x: &[_] = &['1', '2'];
1564 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1567 /// A more complex pattern, using a closure:
1570 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1574 where P::Searcher: DoubleEndedSearcher<'a>
1576 core_str::StrExt::trim_matches(self, pat)
1579 /// Returns a string slice with all prefixes that match a pattern
1580 /// repeatedly removed.
1582 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1583 /// a character matches.
1585 /// [`char`]: primitive.char.html
1592 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1593 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1595 /// let x: &[_] = &['1', '2'];
1596 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1600 core_str::StrExt::trim_left_matches(self, pat)
1603 /// Returns a string slice with all suffixes that match a pattern
1604 /// repeatedly removed.
1606 /// The pattern can be a `&str`, [`char`], or a closure that
1607 /// determines if a character matches.
1609 /// [`char`]: primitive.char.html
1613 /// Simple patterns:
1616 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1617 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1619 /// let x: &[_] = &['1', '2'];
1620 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1623 /// A more complex pattern, using a closure:
1626 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1630 where P::Searcher: ReverseSearcher<'a>
1632 core_str::StrExt::trim_right_matches(self, pat)
1635 /// Parses this string slice into another type.
1637 /// Because `parse()` is so general, it can cause problems with type
1638 /// inference. As such, `parse()` is one of the few times you'll see
1639 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1640 /// helps the inference algorithm understand specifically which type
1641 /// you're trying to parse into.
1643 /// `parse()` can parse any type that implements the [`FromStr`] trait.
1645 /// [`FromStr`]: str/trait.FromStr.html
1649 /// Will return `Err` if it's not possible to parse this string slice into
1650 /// the desired type.
1657 /// let four: u32 = "4".parse().unwrap();
1659 /// assert_eq!(4, four);
1662 /// Using the 'turbofish' instead of annotationg `four`:
1665 /// let four = "4".parse::<u32>();
1667 /// assert_eq!(Ok(4), four);
1670 /// Failing to parse:
1673 /// let nope = "j".parse::<u32>();
1675 /// assert!(nope.is_err());
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1680 core_str::StrExt::parse(self)
1683 /// Replaces all matches of a pattern with another string.
1685 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1686 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1687 /// replaces them with the replacement string slice.
1689 /// [`String`]: string/struct.String.html
1696 /// let s = "this is old";
1698 /// assert_eq!("this is new", s.replace("old", "new"));
1701 /// When the pattern doesn't match:
1704 /// let s = "this is old";
1705 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1707 #[stable(feature = "rust1", since = "1.0.0")]
1708 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1709 let mut result = String::new();
1710 let mut last_end = 0;
1711 for (start, part) in self.match_indices(from) {
1712 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1713 result.push_str(to);
1714 last_end = start + part.len();
1716 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1720 /// Returns the lowercase equivalent of this string slice, as a new `String`.
1722 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1730 /// let s = "HELLO";
1732 /// assert_eq!("hello", s.to_lowercase());
1735 /// A tricky example, with sigma:
1738 /// let sigma = "Σ";
1740 /// assert_eq!("σ", sigma.to_lowercase());
1742 /// // but at the end of a word, it's ς, not σ:
1743 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1745 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1748 /// Languages without case are not changed:
1751 /// let new_year = "农历新年";
1753 /// assert_eq!(new_year, new_year.to_lowercase());
1755 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1756 pub fn to_lowercase(&self) -> String {
1757 let mut s = String::with_capacity(self.len());
1758 for (i, c) in self[..].char_indices() {
1760 // Σ maps to σ, except at the end of a word where it maps to ς.
1761 // This is the only conditional (contextual) but language-independent mapping
1762 // in `SpecialCasing.txt`,
1763 // so hard-code it rather than have a generic "condition" mechanim.
1764 // See https://github.com/rust-lang/rust/issues/26035
1765 map_uppercase_sigma(self, i, &mut s)
1767 s.extend(c.to_lowercase());
1772 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1773 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1774 // for the definition of `Final_Sigma`.
1775 debug_assert!('Σ'.len_utf8() == 2);
1776 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1777 !case_ignoreable_then_cased(from[i + 2..].chars());
1778 to.push_str(if is_word_final {
1785 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1786 use rustc_unicode::derived_property::{Cased, Case_Ignorable};
1787 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1788 Some(c) => Cased(c),
1794 /// Returns the uppercase equivalent of this string slice, as a new `String`.
1796 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1804 /// let s = "hello";
1806 /// assert_eq!("HELLO", s.to_uppercase());
1809 /// Scripts without case are not changed:
1812 /// let new_year = "农历新年";
1814 /// assert_eq!(new_year, new_year.to_uppercase());
1816 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1817 pub fn to_uppercase(&self) -> String {
1818 let mut s = String::with_capacity(self.len());
1819 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1823 /// Escapes each char in `s` with `char::escape_default`.
1824 #[unstable(feature = "str_escape",
1825 reason = "return type may change to be an iterator",
1827 pub fn escape_default(&self) -> String {
1828 self.chars().flat_map(|c| c.escape_default()).collect()
1831 /// Escapes each char in `s` with `char::escape_unicode`.
1832 #[unstable(feature = "str_escape",
1833 reason = "return type may change to be an iterator",
1835 pub fn escape_unicode(&self) -> String {
1836 self.chars().flat_map(|c| c.escape_unicode()).collect()
1839 /// Converts a `Box<str>` into a `String` without copying or allocating.
1846 /// let string = String::from("birthday gift");
1847 /// let boxed_str = string.clone().into_boxed_str();
1849 /// assert_eq!(boxed_str.into_string(), string);
1851 #[stable(feature = "box_str", since = "1.4.0")]
1852 pub fn into_string(self: Box<str>) -> String {
1854 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1855 String::from_utf8_unchecked(slice.into_vec())