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](../../std/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)]
23 use core::str as core_str;
24 use core::str::pattern::Pattern;
25 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
27 use core::iter::FusedIterator;
28 use std_unicode::str::{UnicodeStr, Utf16Encoder};
30 use vec_deque::VecDeque;
31 use borrow::{Borrow, ToOwned};
35 use slice::SliceConcatExt;
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub use core::str::{FromStr, Utf8Error};
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub use core::str::{Lines, LinesAny};
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub use core::str::{Split, RSplit};
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub use core::str::{SplitN, RSplitN};
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub use core::str::{SplitTerminator, RSplitTerminator};
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub use core::str::{Matches, RMatches};
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub use core::str::{MatchIndices, RMatchIndices};
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
55 #[stable(feature = "rust1", since = "1.0.0")]
56 pub use core::str::{from_utf8_unchecked, ParseBoolError};
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub use std_unicode::str::SplitWhitespace;
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub use core::str::pattern;
62 #[unstable(feature = "slice_concat_ext",
63 reason = "trait should not have to exist",
65 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
68 fn concat(&self) -> String {
73 // `len` calculation may overflow but push_str will check boundaries
74 let len = self.iter().map(|s| s.borrow().len()).sum();
75 let mut result = String::with_capacity(len);
78 result.push_str(s.borrow())
84 fn join(&self, sep: &str) -> String {
94 // this is wrong without the guarantee that `self` is non-empty
95 // `len` calculation may overflow but push_str but will check boundaries
96 let len = sep.len() * (self.len() - 1) +
97 self.iter().map(|s| s.borrow().len()).sum::<usize>();
98 let mut result = String::with_capacity(len);
105 result.push_str(sep);
107 result.push_str(s.borrow());
112 fn connect(&self, sep: &str) -> String {
117 /// External iterator for a string's UTF-16 code units.
119 /// For use with the `std::iter` module.
121 #[stable(feature = "encode_utf16", since = "1.8.0")]
122 pub struct EncodeUtf16<'a> {
123 encoder: Utf16Encoder<Chars<'a>>,
126 #[stable(feature = "collection_debug", since = "1.17.0")]
127 impl<'a> fmt::Debug for EncodeUtf16<'a> {
128 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
129 f.pad("EncodeUtf16 { .. }")
133 #[stable(feature = "encode_utf16", since = "1.8.0")]
134 impl<'a> Iterator for EncodeUtf16<'a> {
138 fn next(&mut self) -> Option<u16> {
143 fn size_hint(&self) -> (usize, Option<usize>) {
144 self.encoder.size_hint()
148 #[unstable(feature = "fused", issue = "35602")]
149 impl<'a> FusedIterator for EncodeUtf16<'a> {}
151 // Return the initial codepoint accumulator for the first byte.
152 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
153 // for width 3, and 3 bits for width 4
154 macro_rules! utf8_first_byte {
155 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
158 // return the value of $ch updated with continuation byte $byte
159 macro_rules! utf8_acc_cont_byte {
160 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
163 #[stable(feature = "rust1", since = "1.0.0")]
164 impl Borrow<str> for String {
166 fn borrow(&self) -> &str {
171 #[stable(feature = "rust1", since = "1.0.0")]
172 impl ToOwned for str {
174 fn to_owned(&self) -> String {
175 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
179 /// Methods for string slices.
183 /// Returns the length of `self`.
185 /// This length is in bytes, not [`char`]s or graphemes. In other words,
186 /// it may not be what a human considers the length of the string.
188 /// [`char`]: primitive.char.html
195 /// let len = "foo".len();
196 /// assert_eq!(3, len);
198 /// let len = "ƒoo".len(); // fancy f!
199 /// assert_eq!(4, len);
201 #[stable(feature = "rust1", since = "1.0.0")]
203 pub fn len(&self) -> usize {
204 core_str::StrExt::len(self)
207 /// Returns true if this slice has a length of zero bytes.
215 /// assert!(s.is_empty());
217 /// let s = "not empty";
218 /// assert!(!s.is_empty());
221 #[stable(feature = "rust1", since = "1.0.0")]
222 pub fn is_empty(&self) -> bool {
223 core_str::StrExt::is_empty(self)
226 /// Checks that `index`-th byte lies at the start and/or end of a
227 /// UTF-8 code point sequence.
229 /// The start and end of the string (when `index == self.len()`) are
233 /// Returns `false` if `index` is greater than `self.len()`.
238 /// let s = "Löwe 老虎 Léopard";
239 /// assert!(s.is_char_boundary(0));
241 /// assert!(s.is_char_boundary(6));
242 /// assert!(s.is_char_boundary(s.len()));
244 /// // second byte of `ö`
245 /// assert!(!s.is_char_boundary(2));
247 /// // third byte of `老`
248 /// assert!(!s.is_char_boundary(8));
250 #[stable(feature = "is_char_boundary", since = "1.9.0")]
252 pub fn is_char_boundary(&self, index: usize) -> bool {
253 core_str::StrExt::is_char_boundary(self, index)
256 /// Converts a string slice to a byte slice.
263 /// let bytes = "bors".as_bytes();
264 /// assert_eq!(b"bors", bytes);
266 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn as_bytes(&self) -> &[u8] {
269 core_str::StrExt::as_bytes(self)
272 /// Converts a string slice to a raw pointer.
274 /// As string slices are a slice of bytes, the raw pointer points to a
275 /// [`u8`]. This pointer will be pointing to the first byte of the string
278 /// [`u8`]: primitive.u8.html
286 /// let ptr = s.as_ptr();
288 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn as_ptr(&self) -> *const u8 {
291 core_str::StrExt::as_ptr(self)
294 /// Creates a string slice from another string slice, bypassing safety
297 /// This new slice goes from `begin` to `end`, including `begin` but
300 /// To get a mutable string slice instead, see the
301 /// [`slice_mut_unchecked()`] method.
303 /// [`slice_mut_unchecked()`]: #method.slice_mut_unchecked
307 /// Callers of this function are responsible that three preconditions are
310 /// * `begin` must come before `end`.
311 /// * `begin` and `end` must be byte positions within the string slice.
312 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
319 /// let s = "Löwe 老虎 Léopard";
322 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
325 /// let s = "Hello, world!";
328 /// assert_eq!("world", s.slice_unchecked(7, 12));
331 #[stable(feature = "rust1", since = "1.0.0")]
333 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
334 core_str::StrExt::slice_unchecked(self, begin, end)
337 /// Creates a string slice from another string slice, bypassing safety
340 /// This new slice goes from `begin` to `end`, including `begin` but
343 /// To get an immutable string slice instead, see the
344 /// [`slice_unchecked()`] method.
346 /// [`slice_unchecked()`]: #method.slice_unchecked
350 /// Callers of this function are responsible that three preconditions are
353 /// * `begin` must come before `end`.
354 /// * `begin` and `end` must be byte positions within the string slice.
355 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
356 #[stable(feature = "str_slice_mut", since = "1.5.0")]
358 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
359 core_str::StrExt::slice_mut_unchecked(self, begin, end)
362 /// Divide one string slice into two at an index.
364 /// The argument, `mid`, should be a byte offset from the start of the
365 /// string. It must also be on the boundary of a UTF-8 code point.
367 /// The two slices returned go from the start of the string slice to `mid`,
368 /// and from `mid` to the end of the string slice.
370 /// To get mutable string slices instead, see the [`split_at_mut()`]
373 /// [`split_at_mut()`]: #method.split_at_mut
377 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
378 /// beyond the last code point of the string slice.
385 /// let s = "Per Martin-Löf";
387 /// let (first, last) = s.split_at(3);
389 /// assert_eq!("Per", first);
390 /// assert_eq!(" Martin-Löf", last);
393 #[stable(feature = "str_split_at", since = "1.4.0")]
394 pub fn split_at(&self, mid: usize) -> (&str, &str) {
395 core_str::StrExt::split_at(self, mid)
398 /// Divide one mutable string slice into two at an index.
400 /// The argument, `mid`, should be a byte offset from the start of the
401 /// string. It must also be on the boundary of a UTF-8 code point.
403 /// The two slices returned go from the start of the string slice to `mid`,
404 /// and from `mid` to the end of the string slice.
406 /// To get immutable string slices instead, see the [`split_at()`] method.
408 /// [`split_at()`]: #method.split_at
412 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
413 /// beyond the last code point of the string slice.
420 /// let mut s = "Per Martin-Löf".to_string();
422 /// let (first, last) = s.split_at_mut(3);
424 /// assert_eq!("Per", first);
425 /// assert_eq!(" Martin-Löf", last);
428 #[stable(feature = "str_split_at", since = "1.4.0")]
429 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
430 core_str::StrExt::split_at_mut(self, mid)
433 /// Returns an iterator over the `char`s of a string slice.
435 /// As a string slice consists of valid UTF-8, we can iterate through a
436 /// string slice by [`char`]. This method returns such an iterator.
438 /// It's important to remember that [`char`] represents a Unicode Scalar
439 /// Value, and may not match your idea of what a 'character' is. Iteration
440 /// over grapheme clusters may be what you actually want.
442 /// [`char`]: primitive.char.html
449 /// let word = "goodbye";
451 /// let count = word.chars().count();
452 /// assert_eq!(7, count);
454 /// let mut chars = word.chars();
456 /// assert_eq!(Some('g'), chars.next());
457 /// assert_eq!(Some('o'), chars.next());
458 /// assert_eq!(Some('o'), chars.next());
459 /// assert_eq!(Some('d'), chars.next());
460 /// assert_eq!(Some('b'), chars.next());
461 /// assert_eq!(Some('y'), chars.next());
462 /// assert_eq!(Some('e'), chars.next());
464 /// assert_eq!(None, chars.next());
467 /// Remember, [`char`]s may not match your human intuition about characters:
472 /// let mut chars = y.chars();
474 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
475 /// assert_eq!(Some('\u{0306}'), chars.next());
477 /// assert_eq!(None, chars.next());
479 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn chars(&self) -> Chars {
482 core_str::StrExt::chars(self)
484 /// Returns an iterator over the [`char`]s of a string slice, and their
487 /// As a string slice consists of valid UTF-8, we can iterate through a
488 /// string slice by [`char`]. This method returns an iterator of both
489 /// these [`char`]s, as well as their byte positions.
491 /// The iterator yields tuples. The position is first, the [`char`] is
494 /// [`char`]: primitive.char.html
501 /// let word = "goodbye";
503 /// let count = word.char_indices().count();
504 /// assert_eq!(7, count);
506 /// let mut char_indices = word.char_indices();
508 /// assert_eq!(Some((0, 'g')), char_indices.next());
509 /// assert_eq!(Some((1, 'o')), char_indices.next());
510 /// assert_eq!(Some((2, 'o')), char_indices.next());
511 /// assert_eq!(Some((3, 'd')), char_indices.next());
512 /// assert_eq!(Some((4, 'b')), char_indices.next());
513 /// assert_eq!(Some((5, 'y')), char_indices.next());
514 /// assert_eq!(Some((6, 'e')), char_indices.next());
516 /// assert_eq!(None, char_indices.next());
519 /// Remember, [`char`]s may not match your human intuition about characters:
524 /// let mut char_indices = y.char_indices();
526 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
527 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
529 /// assert_eq!(None, char_indices.next());
531 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn char_indices(&self) -> CharIndices {
534 core_str::StrExt::char_indices(self)
537 /// An iterator over the bytes of a string slice.
539 /// As a string slice consists of a sequence of bytes, we can iterate
540 /// through a string slice by byte. This method returns such an iterator.
547 /// let mut bytes = "bors".bytes();
549 /// assert_eq!(Some(b'b'), bytes.next());
550 /// assert_eq!(Some(b'o'), bytes.next());
551 /// assert_eq!(Some(b'r'), bytes.next());
552 /// assert_eq!(Some(b's'), bytes.next());
554 /// assert_eq!(None, bytes.next());
556 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn bytes(&self) -> Bytes {
559 core_str::StrExt::bytes(self)
562 /// Split a string slice by whitespace.
564 /// The iterator returned will return string slices that are sub-slices of
565 /// the original string slice, separated by any amount of whitespace.
567 /// 'Whitespace' is defined according to the terms of the Unicode Derived
568 /// Core Property `White_Space`.
575 /// let mut iter = "A few words".split_whitespace();
577 /// assert_eq!(Some("A"), iter.next());
578 /// assert_eq!(Some("few"), iter.next());
579 /// assert_eq!(Some("words"), iter.next());
581 /// assert_eq!(None, iter.next());
584 /// All kinds of whitespace are considered:
587 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
588 /// assert_eq!(Some("Mary"), iter.next());
589 /// assert_eq!(Some("had"), iter.next());
590 /// assert_eq!(Some("a"), iter.next());
591 /// assert_eq!(Some("little"), iter.next());
592 /// assert_eq!(Some("lamb"), iter.next());
594 /// assert_eq!(None, iter.next());
596 #[stable(feature = "split_whitespace", since = "1.1.0")]
598 pub fn split_whitespace(&self) -> SplitWhitespace {
599 UnicodeStr::split_whitespace(self)
602 /// An iterator over the lines of a string, as string slices.
604 /// Lines are ended with either a newline (`\n`) or a carriage return with
605 /// a line feed (`\r\n`).
607 /// The final line ending is optional.
614 /// let text = "foo\r\nbar\n\nbaz\n";
615 /// let mut lines = text.lines();
617 /// assert_eq!(Some("foo"), lines.next());
618 /// assert_eq!(Some("bar"), lines.next());
619 /// assert_eq!(Some(""), lines.next());
620 /// assert_eq!(Some("baz"), lines.next());
622 /// assert_eq!(None, lines.next());
625 /// The final line ending isn't required:
628 /// let text = "foo\nbar\n\r\nbaz";
629 /// let mut lines = text.lines();
631 /// assert_eq!(Some("foo"), lines.next());
632 /// assert_eq!(Some("bar"), lines.next());
633 /// assert_eq!(Some(""), lines.next());
634 /// assert_eq!(Some("baz"), lines.next());
636 /// assert_eq!(None, lines.next());
638 #[stable(feature = "rust1", since = "1.0.0")]
640 pub fn lines(&self) -> Lines {
641 core_str::StrExt::lines(self)
644 /// An iterator over the lines of a string.
645 #[stable(feature = "rust1", since = "1.0.0")]
646 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
649 pub fn lines_any(&self) -> LinesAny {
650 core_str::StrExt::lines_any(self)
653 /// Returns an iterator of `u16` over the string encoded as UTF-16.
654 #[stable(feature = "encode_utf16", since = "1.8.0")]
655 pub fn encode_utf16(&self) -> EncodeUtf16 {
656 EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
659 /// Returns `true` if the given pattern matches a sub-slice of
660 /// this string slice.
662 /// Returns `false` if it does not.
669 /// let bananas = "bananas";
671 /// assert!(bananas.contains("nana"));
672 /// assert!(!bananas.contains("apples"));
674 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
676 core_str::StrExt::contains(self, pat)
679 /// Returns `true` if the given pattern matches a prefix of this
682 /// Returns `false` if it does not.
689 /// let bananas = "bananas";
691 /// assert!(bananas.starts_with("bana"));
692 /// assert!(!bananas.starts_with("nana"));
694 #[stable(feature = "rust1", since = "1.0.0")]
695 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
696 core_str::StrExt::starts_with(self, pat)
699 /// Returns `true` if the given pattern matches a suffix of this
702 /// Returns `false` if it does not.
709 /// let bananas = "bananas";
711 /// assert!(bananas.ends_with("anas"));
712 /// assert!(!bananas.ends_with("nana"));
714 #[stable(feature = "rust1", since = "1.0.0")]
715 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
716 where P::Searcher: ReverseSearcher<'a>
718 core_str::StrExt::ends_with(self, pat)
721 /// Returns the byte index of the first character of this string slice that
722 /// matches the pattern.
724 /// Returns [`None`] if the pattern doesn't match.
726 /// The pattern can be a `&str`, [`char`], or a closure that determines if
727 /// a character matches.
729 /// [`char`]: primitive.char.html
730 /// [`None`]: option/enum.Option.html#variant.None
737 /// let s = "Löwe 老虎 Léopard";
739 /// assert_eq!(s.find('L'), Some(0));
740 /// assert_eq!(s.find('é'), Some(14));
741 /// assert_eq!(s.find("Léopard"), Some(13));
744 /// More complex patterns with closures:
747 /// let s = "Löwe 老虎 Léopard";
749 /// assert_eq!(s.find(char::is_whitespace), Some(5));
750 /// assert_eq!(s.find(char::is_lowercase), Some(1));
753 /// Not finding the pattern:
756 /// let s = "Löwe 老虎 Léopard";
757 /// let x: &[_] = &['1', '2'];
759 /// assert_eq!(s.find(x), None);
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
763 core_str::StrExt::find(self, pat)
766 /// Returns the byte index of the last character of this string slice that
767 /// matches the pattern.
769 /// Returns [`None`] if the pattern doesn't match.
771 /// The pattern can be a `&str`, [`char`], or a closure that determines if
772 /// a character matches.
774 /// [`char`]: primitive.char.html
775 /// [`None`]: option/enum.Option.html#variant.None
782 /// let s = "Löwe 老虎 Léopard";
784 /// assert_eq!(s.rfind('L'), Some(13));
785 /// assert_eq!(s.rfind('é'), Some(14));
788 /// More complex patterns with closures:
791 /// let s = "Löwe 老虎 Léopard";
793 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
794 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
797 /// Not finding the pattern:
800 /// let s = "Löwe 老虎 Léopard";
801 /// let x: &[_] = &['1', '2'];
803 /// assert_eq!(s.rfind(x), None);
805 #[stable(feature = "rust1", since = "1.0.0")]
806 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
807 where P::Searcher: ReverseSearcher<'a>
809 core_str::StrExt::rfind(self, pat)
812 /// An iterator over substrings of this string slice, separated by
813 /// characters matched by a pattern.
815 /// The pattern can be a `&str`, [`char`], or a closure that determines the
818 /// # Iterator behavior
820 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
821 /// allows a reverse search and forward/reverse search yields the same
822 /// elements. This is true for, eg, [`char`] but not for `&str`.
824 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
826 /// If the pattern allows a reverse search but its results might differ
827 /// from a forward search, the [`rsplit()`] method can be used.
829 /// [`char`]: primitive.char.html
830 /// [`rsplit()`]: #method.rsplit
837 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
838 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
840 /// let v: Vec<&str> = "".split('X').collect();
841 /// assert_eq!(v, [""]);
843 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
844 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
846 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
847 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
849 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
850 /// assert_eq!(v, ["abc", "def", "ghi"]);
852 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
853 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
856 /// A more complex pattern, using a closure:
859 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
860 /// assert_eq!(v, ["abc", "def", "ghi"]);
863 /// If a string contains multiple contiguous separators, you will end up
864 /// with empty strings in the output:
867 /// let x = "||||a||b|c".to_string();
868 /// let d: Vec<_> = x.split('|').collect();
870 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
873 /// Contiguous separators are separated by the empty string.
876 /// let x = "(///)".to_string();
877 /// let d: Vec<_> = x.split('/').collect();;
879 /// assert_eq!(d, &["(", "", "", ")"]);
882 /// Separators at the start or end of a string are neighbored
883 /// by empty strings.
886 /// let d: Vec<_> = "010".split("0").collect();
887 /// assert_eq!(d, &["", "1", ""]);
890 /// When the empty string is used as a separator, it separates
891 /// every character in the string, along with the beginning
892 /// and end of the string.
895 /// let f: Vec<_> = "rust".split("").collect();
896 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
899 /// Contiguous separators can lead to possibly surprising behavior
900 /// when whitespace is used as the separator. This code is correct:
903 /// let x = " a b c".to_string();
904 /// let d: Vec<_> = x.split(' ').collect();
906 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
909 /// It does _not_ give you:
912 /// assert_eq!(d, &["a", "b", "c"]);
915 /// Use [`split_whitespace()`] for this behavior.
917 /// [`split_whitespace()`]: #method.split_whitespace
918 #[stable(feature = "rust1", since = "1.0.0")]
919 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
920 core_str::StrExt::split(self, pat)
923 /// An iterator over substrings of the given string slice, separated by
924 /// characters matched by a pattern and yielded in reverse order.
926 /// The pattern can be a `&str`, [`char`], or a closure that determines the
929 /// [`char`]: primitive.char.html
931 /// # Iterator behavior
933 /// The returned iterator requires that the pattern supports a reverse
934 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
935 /// search yields the same elements.
937 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
939 /// For iterating from the front, the [`split()`] method can be used.
941 /// [`split()`]: #method.split
948 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
949 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
951 /// let v: Vec<&str> = "".rsplit('X').collect();
952 /// assert_eq!(v, [""]);
954 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
955 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
957 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
958 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
961 /// A more complex pattern, using a closure:
964 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
965 /// assert_eq!(v, ["ghi", "def", "abc"]);
967 #[stable(feature = "rust1", since = "1.0.0")]
968 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
969 where P::Searcher: ReverseSearcher<'a>
971 core_str::StrExt::rsplit(self, pat)
974 /// An iterator over substrings of the given string slice, separated by
975 /// characters matched by a pattern.
977 /// The pattern can be a `&str`, [`char`], or a closure that determines the
980 /// Equivalent to [`split()`], except that the trailing substring
981 /// is skipped if empty.
983 /// [`split()`]: #method.split
985 /// This method can be used for string data that is _terminated_,
986 /// rather than _separated_ by a pattern.
988 /// # Iterator behavior
990 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
991 /// allows a reverse search and forward/reverse search yields the same
992 /// elements. This is true for, eg, [`char`] but not for `&str`.
994 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
995 /// [`char`]: primitive.char.html
997 /// If the pattern allows a reverse search but its results might differ
998 /// from a forward search, the [`rsplit_terminator()`] method can be used.
1000 /// [`rsplit_terminator()`]: #method.rsplit_terminator
1007 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1008 /// assert_eq!(v, ["A", "B"]);
1010 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1011 /// assert_eq!(v, ["A", "", "B", ""]);
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1015 core_str::StrExt::split_terminator(self, pat)
1018 /// An iterator over substrings of `self`, separated by characters
1019 /// matched by a pattern and yielded in reverse order.
1021 /// The pattern can be a simple `&str`, [`char`], or a closure that
1022 /// determines the split.
1023 /// Additional libraries might provide more complex patterns like
1024 /// regular expressions.
1026 /// [`char`]: primitive.char.html
1028 /// Equivalent to [`split()`], except that the trailing substring is
1029 /// skipped if empty.
1031 /// [`split()`]: #method.split
1033 /// This method can be used for string data that is _terminated_,
1034 /// rather than _separated_ by a pattern.
1036 /// # Iterator behavior
1038 /// The returned iterator requires that the pattern supports a
1039 /// reverse search, and it will be double ended if a forward/reverse
1040 /// search yields the same elements.
1042 /// For iterating from the front, the [`split_terminator()`] method can be
1045 /// [`split_terminator()`]: #method.split_terminator
1050 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1051 /// assert_eq!(v, ["B", "A"]);
1053 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1054 /// assert_eq!(v, ["", "B", "", "A"]);
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1058 where P::Searcher: ReverseSearcher<'a>
1060 core_str::StrExt::rsplit_terminator(self, pat)
1063 /// An iterator over substrings of the given string slice, separated by a
1064 /// pattern, restricted to returning at most `n` items.
1066 /// If `n` substrings are returned, the last substring (the `n`th substring)
1067 /// will contain the remainder of the string.
1069 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1072 /// [`char`]: primitive.char.html
1074 /// # Iterator behavior
1076 /// The returned iterator will not be double ended, because it is
1077 /// not efficient to support.
1079 /// If the pattern allows a reverse search, the [`rsplitn()`] method can be
1082 /// [`rsplitn()`]: #method.rsplitn
1086 /// Simple patterns:
1089 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1090 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1092 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1093 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1095 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1096 /// assert_eq!(v, ["abcXdef"]);
1098 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1099 /// assert_eq!(v, [""]);
1102 /// A more complex pattern, using a closure:
1105 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1106 /// assert_eq!(v, ["abc", "defXghi"]);
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1110 core_str::StrExt::splitn(self, n, pat)
1113 /// An iterator over substrings of this string slice, separated by a
1114 /// pattern, starting from the end of the string, restricted to returning
1115 /// at most `n` items.
1117 /// If `n` substrings are returned, the last substring (the `n`th substring)
1118 /// will contain the remainder of the string.
1120 /// The pattern can be a `&str`, [`char`], or a closure that
1121 /// determines the split.
1123 /// [`char`]: primitive.char.html
1125 /// # Iterator behavior
1127 /// The returned iterator will not be double ended, because it is not
1128 /// efficient to support.
1130 /// For splitting from the front, the [`splitn()`] method can be used.
1132 /// [`splitn()`]: #method.splitn
1136 /// Simple patterns:
1139 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1140 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1142 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1143 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1145 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1146 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1149 /// A more complex pattern, using a closure:
1152 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1153 /// assert_eq!(v, ["ghi", "abc1def"]);
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1157 where P::Searcher: ReverseSearcher<'a>
1159 core_str::StrExt::rsplitn(self, n, pat)
1162 /// An iterator over the matches of a pattern within the given string
1165 /// The pattern can be a `&str`, [`char`], or a closure that
1166 /// determines if a character matches.
1168 /// [`char`]: primitive.char.html
1170 /// # Iterator behavior
1172 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1173 /// allows a reverse search and forward/reverse search yields the same
1174 /// elements. This is true for, eg, [`char`] but not for `&str`.
1176 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1177 /// [`char`]: primitive.char.html
1179 /// If the pattern allows a reverse search but its results might differ
1180 /// from a forward search, the [`rmatches()`] method can be used.
1182 /// [`rmatches()`]: #method.rmatches
1189 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1190 /// assert_eq!(v, ["abc", "abc", "abc"]);
1192 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1193 /// assert_eq!(v, ["1", "2", "3"]);
1195 #[stable(feature = "str_matches", since = "1.2.0")]
1196 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1197 core_str::StrExt::matches(self, pat)
1200 /// An iterator over the matches of a pattern within this string slice,
1201 /// yielded in reverse order.
1203 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1204 /// a character matches.
1206 /// [`char`]: primitive.char.html
1208 /// # Iterator behavior
1210 /// The returned iterator requires that the pattern supports a reverse
1211 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1212 /// search yields the same elements.
1214 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1216 /// For iterating from the front, the [`matches()`] method can be used.
1218 /// [`matches()`]: #method.matches
1225 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1226 /// assert_eq!(v, ["abc", "abc", "abc"]);
1228 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1229 /// assert_eq!(v, ["3", "2", "1"]);
1231 #[stable(feature = "str_matches", since = "1.2.0")]
1232 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1233 where P::Searcher: ReverseSearcher<'a>
1235 core_str::StrExt::rmatches(self, pat)
1238 /// An iterator over the disjoint matches of a pattern within this string
1239 /// slice as well as the index that the match starts at.
1241 /// For matches of `pat` within `self` that overlap, only the indices
1242 /// corresponding to the first match are returned.
1244 /// The pattern can be a `&str`, [`char`], or a closure that determines
1245 /// if a character matches.
1247 /// [`char`]: primitive.char.html
1249 /// # Iterator behavior
1251 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1252 /// allows a reverse search and forward/reverse search yields the same
1253 /// elements. This is true for, eg, [`char`] but not for `&str`.
1255 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1257 /// If the pattern allows a reverse search but its results might differ
1258 /// from a forward search, the [`rmatch_indices()`] method can be used.
1260 /// [`rmatch_indices()`]: #method.rmatch_indices
1267 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1268 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1270 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1271 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1273 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1274 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1276 #[stable(feature = "str_match_indices", since = "1.5.0")]
1277 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1278 core_str::StrExt::match_indices(self, pat)
1281 /// An iterator over the disjoint matches of a pattern within `self`,
1282 /// yielded in reverse order along with the index of the match.
1284 /// For matches of `pat` within `self` that overlap, only the indices
1285 /// corresponding to the last match are returned.
1287 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1288 /// character matches.
1290 /// [`char`]: primitive.char.html
1292 /// # Iterator behavior
1294 /// The returned iterator requires that the pattern supports a reverse
1295 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1296 /// search yields the same elements.
1298 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1300 /// For iterating from the front, the [`match_indices()`] method can be used.
1302 /// [`match_indices()`]: #method.match_indices
1309 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1310 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1312 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1313 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1315 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1316 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1318 #[stable(feature = "str_match_indices", since = "1.5.0")]
1319 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1320 where P::Searcher: ReverseSearcher<'a>
1322 core_str::StrExt::rmatch_indices(self, pat)
1325 /// Returns a string slice with leading and trailing whitespace removed.
1327 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1328 /// Core Property `White_Space`.
1335 /// let s = " Hello\tworld\t";
1337 /// assert_eq!("Hello\tworld", s.trim());
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 pub fn trim(&self) -> &str {
1341 UnicodeStr::trim(self)
1344 /// Returns a string slice with leading whitespace removed.
1346 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1347 /// Core Property `White_Space`.
1349 /// # Text directionality
1351 /// A string is a sequence of bytes. 'Left' in this context means the first
1352 /// position of that byte string; for a language like Arabic or Hebrew
1353 /// which are 'right to left' rather than 'left to right', this will be
1354 /// the _right_ side, not the left.
1361 /// let s = " Hello\tworld\t";
1363 /// assert_eq!("Hello\tworld\t", s.trim_left());
1369 /// let s = " English";
1370 /// assert!(Some('E') == s.trim_left().chars().next());
1372 /// let s = " עברית";
1373 /// assert!(Some('ע') == s.trim_left().chars().next());
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 pub fn trim_left(&self) -> &str {
1377 UnicodeStr::trim_left(self)
1380 /// Returns a string slice with trailing whitespace removed.
1382 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1383 /// Core Property `White_Space`.
1385 /// # Text directionality
1387 /// A string is a sequence of bytes. 'Right' in this context means the last
1388 /// position of that byte string; for a language like Arabic or Hebrew
1389 /// which are 'right to left' rather than 'left to right', this will be
1390 /// the _left_ side, not the right.
1397 /// let s = " Hello\tworld\t";
1399 /// assert_eq!(" Hello\tworld", s.trim_right());
1405 /// let s = "English ";
1406 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1408 /// let s = "עברית ";
1409 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 pub fn trim_right(&self) -> &str {
1413 UnicodeStr::trim_right(self)
1416 /// Returns a string slice with all prefixes and suffixes that match a
1417 /// pattern repeatedly removed.
1419 /// The pattern can be a [`char`] or a closure that determines if a
1420 /// character matches.
1422 /// [`char`]: primitive.char.html
1426 /// Simple patterns:
1429 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1430 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1432 /// let x: &[_] = &['1', '2'];
1433 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1436 /// A more complex pattern, using a closure:
1439 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1443 where P::Searcher: DoubleEndedSearcher<'a>
1445 core_str::StrExt::trim_matches(self, pat)
1448 /// Returns a string slice with all prefixes that match a pattern
1449 /// repeatedly removed.
1451 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1452 /// a character matches.
1454 /// [`char`]: primitive.char.html
1456 /// # Text directionality
1458 /// A string is a sequence of bytes. 'Left' in this context means the first
1459 /// position of that byte string; for a language like Arabic or Hebrew
1460 /// which are 'right to left' rather than 'left to right', this will be
1461 /// the _right_ side, not the left.
1468 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1469 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1471 /// let x: &[_] = &['1', '2'];
1472 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1476 core_str::StrExt::trim_left_matches(self, pat)
1479 /// Returns a string slice with all suffixes that match a pattern
1480 /// repeatedly removed.
1482 /// The pattern can be a `&str`, [`char`], or a closure that
1483 /// determines if a character matches.
1485 /// [`char`]: primitive.char.html
1487 /// # Text directionality
1489 /// A string is a sequence of bytes. 'Right' in this context means the last
1490 /// position of that byte string; for a language like Arabic or Hebrew
1491 /// which are 'right to left' rather than 'left to right', this will be
1492 /// the _left_ side, not the right.
1496 /// Simple patterns:
1499 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1500 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1502 /// let x: &[_] = &['1', '2'];
1503 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1506 /// A more complex pattern, using a closure:
1509 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1513 where P::Searcher: ReverseSearcher<'a>
1515 core_str::StrExt::trim_right_matches(self, pat)
1518 /// Parses this string slice into another type.
1520 /// Because `parse()` is so general, it can cause problems with type
1521 /// inference. As such, `parse()` is one of the few times you'll see
1522 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1523 /// helps the inference algorithm understand specifically which type
1524 /// you're trying to parse into.
1526 /// `parse()` can parse any type that implements the [`FromStr`] trait.
1528 /// [`FromStr`]: str/trait.FromStr.html
1532 /// Will return [`Err`] if it's not possible to parse this string slice into
1533 /// the desired type.
1535 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1542 /// let four: u32 = "4".parse().unwrap();
1544 /// assert_eq!(4, four);
1547 /// Using the 'turbofish' instead of annotating `four`:
1550 /// let four = "4".parse::<u32>();
1552 /// assert_eq!(Ok(4), four);
1555 /// Failing to parse:
1558 /// let nope = "j".parse::<u32>();
1560 /// assert!(nope.is_err());
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1565 core_str::StrExt::parse(self)
1568 /// Replaces all matches of a pattern with another string.
1570 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1571 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1572 /// replaces them with the replacement string slice.
1574 /// [`String`]: string/struct.String.html
1581 /// let s = "this is old";
1583 /// assert_eq!("this is new", s.replace("old", "new"));
1586 /// When the pattern doesn't match:
1589 /// let s = "this is old";
1590 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1594 let mut result = String::new();
1595 let mut last_end = 0;
1596 for (start, part) in self.match_indices(from) {
1597 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1598 result.push_str(to);
1599 last_end = start + part.len();
1601 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1605 /// Replaces first N matches of a pattern with another string.
1607 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1608 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1609 /// replaces them with the replacement string slice at most `N` times.
1611 /// [`String`]: string/struct.String.html
1618 /// let s = "foo foo 123 foo";
1619 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1620 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1621 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1624 /// When the pattern doesn't match:
1627 /// let s = "this is old";
1628 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1630 #[stable(feature = "str_replacen", since = "1.16.0")]
1631 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1632 // Hope to reduce the times of re-allocation
1633 let mut result = String::with_capacity(32);
1634 let mut last_end = 0;
1635 for (start, part) in self.match_indices(pat).take(count) {
1636 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1637 result.push_str(to);
1638 last_end = start + part.len();
1640 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1644 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1646 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1649 /// [`String`]: string/struct.String.html
1656 /// let s = "HELLO";
1658 /// assert_eq!("hello", s.to_lowercase());
1661 /// A tricky example, with sigma:
1664 /// let sigma = "Σ";
1666 /// assert_eq!("σ", sigma.to_lowercase());
1668 /// // but at the end of a word, it's ς, not σ:
1669 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1671 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1674 /// Languages without case are not changed:
1677 /// let new_year = "农历新年";
1679 /// assert_eq!(new_year, new_year.to_lowercase());
1681 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1682 pub fn to_lowercase(&self) -> String {
1683 let mut s = String::with_capacity(self.len());
1684 for (i, c) in self[..].char_indices() {
1686 // Σ maps to σ, except at the end of a word where it maps to ς.
1687 // This is the only conditional (contextual) but language-independent mapping
1688 // in `SpecialCasing.txt`,
1689 // so hard-code it rather than have a generic "condition" mechanism.
1690 // See https://github.com/rust-lang/rust/issues/26035
1691 map_uppercase_sigma(self, i, &mut s)
1693 s.extend(c.to_lowercase());
1698 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1699 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1700 // for the definition of `Final_Sigma`.
1701 debug_assert!('Σ'.len_utf8() == 2);
1702 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1703 !case_ignoreable_then_cased(from[i + 2..].chars());
1704 to.push_str(if is_word_final { "ς" } else { "σ" });
1707 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1708 use std_unicode::derived_property::{Cased, Case_Ignorable};
1709 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1710 Some(c) => Cased(c),
1716 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1718 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1721 /// [`String`]: string/struct.String.html
1728 /// let s = "hello";
1730 /// assert_eq!("HELLO", s.to_uppercase());
1733 /// Scripts without case are not changed:
1736 /// let new_year = "农历新年";
1738 /// assert_eq!(new_year, new_year.to_uppercase());
1740 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1741 pub fn to_uppercase(&self) -> String {
1742 let mut s = String::with_capacity(self.len());
1743 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1747 /// Escapes each char in `s` with `char::escape_debug`.
1748 #[unstable(feature = "str_escape",
1749 reason = "return type may change to be an iterator",
1751 pub fn escape_debug(&self) -> String {
1752 self.chars().flat_map(|c| c.escape_debug()).collect()
1755 /// Escapes each char in `s` with `char::escape_default`.
1756 #[unstable(feature = "str_escape",
1757 reason = "return type may change to be an iterator",
1759 pub fn escape_default(&self) -> String {
1760 self.chars().flat_map(|c| c.escape_default()).collect()
1763 /// Escapes each char in `s` with `char::escape_unicode`.
1764 #[unstable(feature = "str_escape",
1765 reason = "return type may change to be an iterator",
1767 pub fn escape_unicode(&self) -> String {
1768 self.chars().flat_map(|c| c.escape_unicode()).collect()
1771 /// Converts a `Box<str>` into a [`String`] without copying or allocating.
1773 /// [`String`]: string/struct.String.html
1780 /// let string = String::from("birthday gift");
1781 /// let boxed_str = string.clone().into_boxed_str();
1783 /// assert_eq!(boxed_str.into_string(), string);
1785 #[stable(feature = "box_str", since = "1.4.0")]
1786 pub fn into_string(self: Box<str>) -> String {
1788 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1789 String::from_utf8_unchecked(slice.into_vec())
1793 /// Create a [`String`] by repeating a string `n` times.
1795 /// [`String`]: string/struct.String.html
1802 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
1804 #[stable(feature = "repeat_str", since = "1.16.0")]
1805 pub fn repeat(&self, n: usize) -> String {
1806 let mut s = String::with_capacity(self.len() * n);
1807 s.extend((0..n).map(|_| self));