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 //! The `&str` type is one of the two main string types, the other being `String`.
14 //! Unlike its `String` counterpart, its contents are borrowed.
18 //! A basic string declaration of `&str` type:
21 //! let hello_world = "Hello, World!";
24 //! Here we have declared a string literal, also known as a string slice.
25 //! String literals have a static lifetime, which means the string `hello_world`
26 //! is guaranteed to be valid for the duration of the entire program.
27 //! We can explicitly specify `hello_world`'s lifetime as well:
30 //! let hello_world: &'static str = "Hello, world!";
33 //! *[See also the `str` primitive type](../../std/primitive.str.html).*
35 #![stable(feature = "rust1", since = "1.0.0")]
37 // Many of the usings in this module are only used in the test configuration.
38 // It's cleaner to just turn off the unused_imports warning than to fix them.
39 #![allow(unused_imports)]
42 use core::str as core_str;
43 use core::str::pattern::Pattern;
44 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
46 use core::iter::FusedIterator;
47 use std_unicode::str::{UnicodeStr, Utf16Encoder};
49 use vec_deque::VecDeque;
50 use borrow::{Borrow, ToOwned};
54 use slice::{SliceConcatExt, SliceIndex};
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub use core::str::{FromStr, Utf8Error};
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub use core::str::{Lines, LinesAny};
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub use core::str::{Split, RSplit};
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub use core::str::{SplitN, RSplitN};
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub use core::str::{SplitTerminator, RSplitTerminator};
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use core::str::{Matches, RMatches};
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub use core::str::{MatchIndices, RMatchIndices};
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub use core::str::{from_utf8, from_utf8_mut, Chars, CharIndices, Bytes};
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError};
76 #[unstable(feature = "str_box_extras", issue = "41119")]
77 pub use alloc::str::from_boxed_utf8_unchecked;
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use std_unicode::str::SplitWhitespace;
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub use core::str::pattern;
84 #[unstable(feature = "slice_concat_ext",
85 reason = "trait should not have to exist",
87 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
90 fn concat(&self) -> String {
95 // `len` calculation may overflow but push_str will check boundaries
96 let len = self.iter().map(|s| s.borrow().len()).sum();
97 let mut result = String::with_capacity(len);
100 result.push_str(s.borrow())
106 fn join(&self, sep: &str) -> String {
108 return String::new();
113 return self.concat();
116 // this is wrong without the guarantee that `self` is non-empty
117 // `len` calculation may overflow but push_str but will check boundaries
118 let len = sep.len() * (self.len() - 1) +
119 self.iter().map(|s| s.borrow().len()).sum::<usize>();
120 let mut result = String::with_capacity(len);
121 let mut first = true;
127 result.push_str(sep);
129 result.push_str(s.borrow());
134 fn connect(&self, sep: &str) -> String {
139 /// An iterator of [`u16`] over the string encoded as UTF-16.
141 /// [`u16`]: ../../std/primitive.u16.html
143 /// This struct is created by the [`encode_utf16`] method on [`str`].
144 /// See its documentation for more.
146 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
147 /// [`str`]: ../../std/primitive.str.html
149 #[stable(feature = "encode_utf16", since = "1.8.0")]
150 pub struct EncodeUtf16<'a> {
151 encoder: Utf16Encoder<Chars<'a>>,
154 #[stable(feature = "collection_debug", since = "1.17.0")]
155 impl<'a> fmt::Debug for EncodeUtf16<'a> {
156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157 f.pad("EncodeUtf16 { .. }")
161 #[stable(feature = "encode_utf16", since = "1.8.0")]
162 impl<'a> Iterator for EncodeUtf16<'a> {
166 fn next(&mut self) -> Option<u16> {
171 fn size_hint(&self) -> (usize, Option<usize>) {
172 self.encoder.size_hint()
176 #[unstable(feature = "fused", issue = "35602")]
177 impl<'a> FusedIterator for EncodeUtf16<'a> {}
179 #[stable(feature = "rust1", since = "1.0.0")]
180 impl Borrow<str> for String {
182 fn borrow(&self) -> &str {
187 #[stable(feature = "rust1", since = "1.0.0")]
188 impl ToOwned for str {
190 fn to_owned(&self) -> String {
191 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
194 fn clone_into(&self, target: &mut String) {
195 let mut b = mem::replace(target, String::new()).into_bytes();
196 self.as_bytes().clone_into(&mut b);
197 *target = unsafe { String::from_utf8_unchecked(b) }
201 /// Methods for string slices.
205 /// Returns the length of `self`.
207 /// This length is in bytes, not [`char`]s or graphemes. In other words,
208 /// it may not be what a human considers the length of the string.
210 /// [`char`]: primitive.char.html
217 /// let len = "foo".len();
218 /// assert_eq!(3, len);
220 /// let len = "ƒoo".len(); // fancy f!
221 /// assert_eq!(4, len);
223 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn len(&self) -> usize {
226 core_str::StrExt::len(self)
229 /// Returns `true` if `self` has a length of zero bytes.
237 /// assert!(s.is_empty());
239 /// let s = "not empty";
240 /// assert!(!s.is_empty());
243 #[stable(feature = "rust1", since = "1.0.0")]
244 pub fn is_empty(&self) -> bool {
245 core_str::StrExt::is_empty(self)
248 /// Checks that `index`-th byte lies at the start and/or end of a
249 /// UTF-8 code point sequence.
251 /// The start and end of the string (when `index == self.len()`) are
255 /// Returns `false` if `index` is greater than `self.len()`.
260 /// let s = "Löwe 老虎 Léopard";
261 /// assert!(s.is_char_boundary(0));
263 /// assert!(s.is_char_boundary(6));
264 /// assert!(s.is_char_boundary(s.len()));
266 /// // second byte of `ö`
267 /// assert!(!s.is_char_boundary(2));
269 /// // third byte of `老`
270 /// assert!(!s.is_char_boundary(8));
272 #[stable(feature = "is_char_boundary", since = "1.9.0")]
274 pub fn is_char_boundary(&self, index: usize) -> bool {
275 core_str::StrExt::is_char_boundary(self, index)
278 /// Converts a string slice to a byte slice.
285 /// let bytes = "bors".as_bytes();
286 /// assert_eq!(b"bors", bytes);
288 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn as_bytes(&self) -> &[u8] {
291 core_str::StrExt::as_bytes(self)
294 /// Converts a mutable string slice to a mutable byte slice.
295 #[unstable(feature = "str_mut_extras", issue = "41119")]
297 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
298 core_str::StrExt::as_bytes_mut(self)
301 /// Converts a string slice to a raw pointer.
303 /// As string slices are a slice of bytes, the raw pointer points to a
304 /// [`u8`]. This pointer will be pointing to the first byte of the string
307 /// [`u8`]: primitive.u8.html
315 /// let ptr = s.as_ptr();
317 #[stable(feature = "rust1", since = "1.0.0")]
319 pub fn as_ptr(&self) -> *const u8 {
320 core_str::StrExt::as_ptr(self)
323 /// Returns a subslice of `str`.
325 /// This is the non-panicking alternative to indexing the `str`. Returns
326 /// [`None`] whenever equivalent indexing operation would panic.
328 /// [`None`]: option/enum.Option.html#variant.None
333 /// # #![feature(str_checked_slicing)]
335 /// assert_eq!(Some("🗻"), v.get(0..4));
336 /// assert!(v.get(1..).is_none());
337 /// assert!(v.get(..8).is_none());
338 /// assert!(v.get(..42).is_none());
340 #[unstable(feature = "str_checked_slicing", issue = "39932")]
342 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
343 core_str::StrExt::get(self, i)
346 /// Returns a mutable subslice of `str`.
348 /// This is the non-panicking alternative to indexing the `str`. Returns
349 /// [`None`] whenever equivalent indexing operation would panic.
351 /// [`None`]: option/enum.Option.html#variant.None
356 /// # #![feature(str_checked_slicing)]
357 /// let mut v = String::from("🗻∈🌏");
358 /// assert_eq!(Some("🗻"), v.get_mut(0..4).map(|v| &*v));
359 /// assert!(v.get_mut(1..).is_none());
360 /// assert!(v.get_mut(..8).is_none());
361 /// assert!(v.get_mut(..42).is_none());
363 #[unstable(feature = "str_checked_slicing", issue = "39932")]
365 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
366 core_str::StrExt::get_mut(self, i)
369 /// Returns a unchecked subslice of `str`.
371 /// This is the unchecked alternative to indexing the `str`.
375 /// Callers of this function are responsible that these preconditions are
378 /// * The starting index must come before the ending index;
379 /// * Indexes must be within bounds of the original slice;
380 /// * Indexes must lie on UTF-8 sequence boundaries.
382 /// Failing that, the returned string slice may reference invalid memory or
383 /// violate the invariants communicated by the `str` type.
388 /// # #![feature(str_checked_slicing)]
391 /// assert_eq!("🗻", v.get_unchecked(0..4));
392 /// assert_eq!("∈", v.get_unchecked(4..7));
393 /// assert_eq!("🌏", v.get_unchecked(7..11));
396 #[unstable(feature = "str_checked_slicing", issue = "39932")]
398 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
399 core_str::StrExt::get_unchecked(self, i)
402 /// Returns a mutable, unchecked subslice of `str`.
404 /// This is the unchecked alternative to indexing the `str`.
408 /// Callers of this function are responsible that these preconditions are
411 /// * The starting index must come before the ending index;
412 /// * Indexes must be within bounds of the original slice;
413 /// * Indexes must lie on UTF-8 sequence boundaries.
415 /// Failing that, the returned string slice may reference invalid memory or
416 /// violate the invariants communicated by the `str` type.
421 /// # #![feature(str_checked_slicing)]
422 /// let mut v = String::from("🗻∈🌏");
424 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
425 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
426 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
429 #[unstable(feature = "str_checked_slicing", issue = "39932")]
431 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
432 core_str::StrExt::get_unchecked_mut(self, i)
435 /// Creates a string slice from another string slice, bypassing safety
438 /// This new slice goes from `begin` to `end`, including `begin` but
441 /// To get a mutable string slice instead, see the
442 /// [`slice_mut_unchecked`] method.
444 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
448 /// Callers of this function are responsible that three preconditions are
451 /// * `begin` must come before `end`.
452 /// * `begin` and `end` must be byte positions within the string slice.
453 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
460 /// let s = "Löwe 老虎 Léopard";
463 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
466 /// let s = "Hello, world!";
469 /// assert_eq!("world", s.slice_unchecked(7, 12));
472 #[stable(feature = "rust1", since = "1.0.0")]
474 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
475 core_str::StrExt::slice_unchecked(self, begin, end)
478 /// Creates a string slice from another string slice, bypassing safety
481 /// This new slice goes from `begin` to `end`, including `begin` but
484 /// To get an immutable string slice instead, see the
485 /// [`slice_unchecked`] method.
487 /// [`slice_unchecked`]: #method.slice_unchecked
491 /// Callers of this function are responsible that three preconditions are
494 /// * `begin` must come before `end`.
495 /// * `begin` and `end` must be byte positions within the string slice.
496 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
497 #[stable(feature = "str_slice_mut", since = "1.5.0")]
499 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
500 core_str::StrExt::slice_mut_unchecked(self, begin, end)
503 /// Divide one string slice into two at an index.
505 /// The argument, `mid`, should be a byte offset from the start of the
506 /// string. It must also be on the boundary of a UTF-8 code point.
508 /// The two slices returned go from the start of the string slice to `mid`,
509 /// and from `mid` to the end of the string slice.
511 /// To get mutable string slices instead, see the [`split_at_mut`]
514 /// [`split_at_mut`]: #method.split_at_mut
518 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
519 /// beyond the last code point of the string slice.
526 /// let s = "Per Martin-Löf";
528 /// let (first, last) = s.split_at(3);
530 /// assert_eq!("Per", first);
531 /// assert_eq!(" Martin-Löf", last);
534 #[stable(feature = "str_split_at", since = "1.4.0")]
535 pub fn split_at(&self, mid: usize) -> (&str, &str) {
536 core_str::StrExt::split_at(self, mid)
539 /// Divide one mutable string slice into two at an index.
541 /// The argument, `mid`, should be a byte offset from the start of the
542 /// string. It must also be on the boundary of a UTF-8 code point.
544 /// The two slices returned go from the start of the string slice to `mid`,
545 /// and from `mid` to the end of the string slice.
547 /// To get immutable string slices instead, see the [`split_at`] method.
549 /// [`split_at`]: #method.split_at
553 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
554 /// beyond the last code point of the string slice.
561 /// let mut s = "Per Martin-Löf".to_string();
563 /// let (first, last) = s.split_at_mut(3);
565 /// assert_eq!("Per", first);
566 /// assert_eq!(" Martin-Löf", last);
569 #[stable(feature = "str_split_at", since = "1.4.0")]
570 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
571 core_str::StrExt::split_at_mut(self, mid)
574 /// Returns an iterator over the [`char`]s of a string slice.
576 /// As a string slice consists of valid UTF-8, we can iterate through a
577 /// string slice by [`char`]. This method returns such an iterator.
579 /// It's important to remember that [`char`] represents a Unicode Scalar
580 /// Value, and may not match your idea of what a 'character' is. Iteration
581 /// over grapheme clusters may be what you actually want.
583 /// [`char`]: primitive.char.html
590 /// let word = "goodbye";
592 /// let count = word.chars().count();
593 /// assert_eq!(7, count);
595 /// let mut chars = word.chars();
597 /// assert_eq!(Some('g'), chars.next());
598 /// assert_eq!(Some('o'), chars.next());
599 /// assert_eq!(Some('o'), chars.next());
600 /// assert_eq!(Some('d'), chars.next());
601 /// assert_eq!(Some('b'), chars.next());
602 /// assert_eq!(Some('y'), chars.next());
603 /// assert_eq!(Some('e'), chars.next());
605 /// assert_eq!(None, chars.next());
608 /// Remember, [`char`]s may not match your human intuition about characters:
613 /// let mut chars = y.chars();
615 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
616 /// assert_eq!(Some('\u{0306}'), chars.next());
618 /// assert_eq!(None, chars.next());
620 #[stable(feature = "rust1", since = "1.0.0")]
622 pub fn chars(&self) -> Chars {
623 core_str::StrExt::chars(self)
625 /// Returns an iterator over the [`char`]s of a string slice, and their
628 /// As a string slice consists of valid UTF-8, we can iterate through a
629 /// string slice by [`char`]. This method returns an iterator of both
630 /// these [`char`]s, as well as their byte positions.
632 /// The iterator yields tuples. The position is first, the [`char`] is
635 /// [`char`]: primitive.char.html
642 /// let word = "goodbye";
644 /// let count = word.char_indices().count();
645 /// assert_eq!(7, count);
647 /// let mut char_indices = word.char_indices();
649 /// assert_eq!(Some((0, 'g')), char_indices.next());
650 /// assert_eq!(Some((1, 'o')), char_indices.next());
651 /// assert_eq!(Some((2, 'o')), char_indices.next());
652 /// assert_eq!(Some((3, 'd')), char_indices.next());
653 /// assert_eq!(Some((4, 'b')), char_indices.next());
654 /// assert_eq!(Some((5, 'y')), char_indices.next());
655 /// assert_eq!(Some((6, 'e')), char_indices.next());
657 /// assert_eq!(None, char_indices.next());
660 /// Remember, [`char`]s may not match your human intuition about characters:
665 /// let mut char_indices = y.char_indices();
667 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
668 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
670 /// assert_eq!(None, char_indices.next());
672 #[stable(feature = "rust1", since = "1.0.0")]
674 pub fn char_indices(&self) -> CharIndices {
675 core_str::StrExt::char_indices(self)
678 /// An iterator over the bytes of a string slice.
680 /// As a string slice consists of a sequence of bytes, we can iterate
681 /// through a string slice by byte. This method returns such an iterator.
688 /// let mut bytes = "bors".bytes();
690 /// assert_eq!(Some(b'b'), bytes.next());
691 /// assert_eq!(Some(b'o'), bytes.next());
692 /// assert_eq!(Some(b'r'), bytes.next());
693 /// assert_eq!(Some(b's'), bytes.next());
695 /// assert_eq!(None, bytes.next());
697 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn bytes(&self) -> Bytes {
700 core_str::StrExt::bytes(self)
703 /// Split a string slice by whitespace.
705 /// The iterator returned will return string slices that are sub-slices of
706 /// the original string slice, separated by any amount of whitespace.
708 /// 'Whitespace' is defined according to the terms of the Unicode Derived
709 /// Core Property `White_Space`.
716 /// let mut iter = "A few words".split_whitespace();
718 /// assert_eq!(Some("A"), iter.next());
719 /// assert_eq!(Some("few"), iter.next());
720 /// assert_eq!(Some("words"), iter.next());
722 /// assert_eq!(None, iter.next());
725 /// All kinds of whitespace are considered:
728 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
729 /// assert_eq!(Some("Mary"), iter.next());
730 /// assert_eq!(Some("had"), iter.next());
731 /// assert_eq!(Some("a"), iter.next());
732 /// assert_eq!(Some("little"), iter.next());
733 /// assert_eq!(Some("lamb"), iter.next());
735 /// assert_eq!(None, iter.next());
737 #[stable(feature = "split_whitespace", since = "1.1.0")]
739 pub fn split_whitespace(&self) -> SplitWhitespace {
740 UnicodeStr::split_whitespace(self)
743 /// An iterator over the lines of a string, as string slices.
745 /// Lines are ended with either a newline (`\n`) or a carriage return with
746 /// a line feed (`\r\n`).
748 /// The final line ending is optional.
755 /// let text = "foo\r\nbar\n\nbaz\n";
756 /// let mut lines = text.lines();
758 /// assert_eq!(Some("foo"), lines.next());
759 /// assert_eq!(Some("bar"), lines.next());
760 /// assert_eq!(Some(""), lines.next());
761 /// assert_eq!(Some("baz"), lines.next());
763 /// assert_eq!(None, lines.next());
766 /// The final line ending isn't required:
769 /// let text = "foo\nbar\n\r\nbaz";
770 /// let mut lines = text.lines();
772 /// assert_eq!(Some("foo"), lines.next());
773 /// assert_eq!(Some("bar"), lines.next());
774 /// assert_eq!(Some(""), lines.next());
775 /// assert_eq!(Some("baz"), lines.next());
777 /// assert_eq!(None, lines.next());
779 #[stable(feature = "rust1", since = "1.0.0")]
781 pub fn lines(&self) -> Lines {
782 core_str::StrExt::lines(self)
785 /// An iterator over the lines of a string.
786 #[stable(feature = "rust1", since = "1.0.0")]
787 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
790 pub fn lines_any(&self) -> LinesAny {
791 core_str::StrExt::lines_any(self)
794 /// Returns an iterator of `u16` over the string encoded as UTF-16.
795 #[stable(feature = "encode_utf16", since = "1.8.0")]
796 pub fn encode_utf16(&self) -> EncodeUtf16 {
797 EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
800 /// Returns `true` if the given pattern matches a sub-slice of
801 /// this string slice.
803 /// Returns `false` if it does not.
810 /// let bananas = "bananas";
812 /// assert!(bananas.contains("nana"));
813 /// assert!(!bananas.contains("apples"));
815 #[stable(feature = "rust1", since = "1.0.0")]
817 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
818 core_str::StrExt::contains(self, pat)
821 /// Returns `true` if the given pattern matches a prefix of this
824 /// Returns `false` if it does not.
831 /// let bananas = "bananas";
833 /// assert!(bananas.starts_with("bana"));
834 /// assert!(!bananas.starts_with("nana"));
836 #[stable(feature = "rust1", since = "1.0.0")]
837 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
838 core_str::StrExt::starts_with(self, pat)
841 /// Returns `true` if the given pattern matches a suffix of this
844 /// Returns `false` if it does not.
851 /// let bananas = "bananas";
853 /// assert!(bananas.ends_with("anas"));
854 /// assert!(!bananas.ends_with("nana"));
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
858 where P::Searcher: ReverseSearcher<'a>
860 core_str::StrExt::ends_with(self, pat)
863 /// Returns the byte index of the first character of this string slice that
864 /// matches the pattern.
866 /// Returns [`None`] if the pattern doesn't match.
868 /// The pattern can be a `&str`, [`char`], or a closure that determines if
869 /// a character matches.
871 /// [`char`]: primitive.char.html
872 /// [`None`]: option/enum.Option.html#variant.None
879 /// let s = "Löwe 老虎 Léopard";
881 /// assert_eq!(s.find('L'), Some(0));
882 /// assert_eq!(s.find('é'), Some(14));
883 /// assert_eq!(s.find("Léopard"), Some(13));
886 /// More complex patterns with closures:
889 /// let s = "Löwe 老虎 Léopard";
891 /// assert_eq!(s.find(char::is_whitespace), Some(5));
892 /// assert_eq!(s.find(char::is_lowercase), Some(1));
895 /// Not finding the pattern:
898 /// let s = "Löwe 老虎 Léopard";
899 /// let x: &[_] = &['1', '2'];
901 /// assert_eq!(s.find(x), None);
903 #[stable(feature = "rust1", since = "1.0.0")]
905 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
906 core_str::StrExt::find(self, pat)
909 /// Returns the byte index of the last character of this string slice that
910 /// matches the pattern.
912 /// Returns [`None`] if the pattern doesn't match.
914 /// The pattern can be a `&str`, [`char`], or a closure that determines if
915 /// a character matches.
917 /// [`char`]: primitive.char.html
918 /// [`None`]: option/enum.Option.html#variant.None
925 /// let s = "Löwe 老虎 Léopard";
927 /// assert_eq!(s.rfind('L'), Some(13));
928 /// assert_eq!(s.rfind('é'), Some(14));
931 /// More complex patterns with closures:
934 /// let s = "Löwe 老虎 Léopard";
936 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
937 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
940 /// Not finding the pattern:
943 /// let s = "Löwe 老虎 Léopard";
944 /// let x: &[_] = &['1', '2'];
946 /// assert_eq!(s.rfind(x), None);
948 #[stable(feature = "rust1", since = "1.0.0")]
950 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
951 where P::Searcher: ReverseSearcher<'a>
953 core_str::StrExt::rfind(self, pat)
956 /// An iterator over substrings of this string slice, separated by
957 /// characters matched by a pattern.
959 /// The pattern can be a `&str`, [`char`], or a closure that determines the
962 /// # Iterator behavior
964 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
965 /// allows a reverse search and forward/reverse search yields the same
966 /// elements. This is true for, eg, [`char`] but not for `&str`.
968 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
970 /// If the pattern allows a reverse search but its results might differ
971 /// from a forward search, the [`rsplit`] method can be used.
973 /// [`char`]: primitive.char.html
974 /// [`rsplit`]: #method.rsplit
981 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
982 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
984 /// let v: Vec<&str> = "".split('X').collect();
985 /// assert_eq!(v, [""]);
987 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
988 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
990 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
991 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
993 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
994 /// assert_eq!(v, ["abc", "def", "ghi"]);
996 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
997 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1000 /// A more complex pattern, using a closure:
1003 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1004 /// assert_eq!(v, ["abc", "def", "ghi"]);
1007 /// If a string contains multiple contiguous separators, you will end up
1008 /// with empty strings in the output:
1011 /// let x = "||||a||b|c".to_string();
1012 /// let d: Vec<_> = x.split('|').collect();
1014 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1017 /// Contiguous separators are separated by the empty string.
1020 /// let x = "(///)".to_string();
1021 /// let d: Vec<_> = x.split('/').collect();
1023 /// assert_eq!(d, &["(", "", "", ")"]);
1026 /// Separators at the start or end of a string are neighbored
1027 /// by empty strings.
1030 /// let d: Vec<_> = "010".split("0").collect();
1031 /// assert_eq!(d, &["", "1", ""]);
1034 /// When the empty string is used as a separator, it separates
1035 /// every character in the string, along with the beginning
1036 /// and end of the string.
1039 /// let f: Vec<_> = "rust".split("").collect();
1040 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1043 /// Contiguous separators can lead to possibly surprising behavior
1044 /// when whitespace is used as the separator. This code is correct:
1047 /// let x = " a b c".to_string();
1048 /// let d: Vec<_> = x.split(' ').collect();
1050 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1053 /// It does _not_ give you:
1056 /// assert_eq!(d, &["a", "b", "c"]);
1059 /// Use [`split_whitespace`] for this behavior.
1061 /// [`split_whitespace`]: #method.split_whitespace
1062 #[stable(feature = "rust1", since = "1.0.0")]
1064 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1065 core_str::StrExt::split(self, pat)
1068 /// An iterator over substrings of the given string slice, separated by
1069 /// characters matched by a pattern and yielded in reverse order.
1071 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1074 /// [`char`]: primitive.char.html
1076 /// # Iterator behavior
1078 /// The returned iterator requires that the pattern supports a reverse
1079 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1080 /// search yields the same elements.
1082 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1084 /// For iterating from the front, the [`split`] method can be used.
1086 /// [`split`]: #method.split
1090 /// Simple patterns:
1093 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1094 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1096 /// let v: Vec<&str> = "".rsplit('X').collect();
1097 /// assert_eq!(v, [""]);
1099 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1100 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1102 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1103 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1106 /// A more complex pattern, using a closure:
1109 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1110 /// assert_eq!(v, ["ghi", "def", "abc"]);
1112 #[stable(feature = "rust1", since = "1.0.0")]
1114 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1115 where P::Searcher: ReverseSearcher<'a>
1117 core_str::StrExt::rsplit(self, pat)
1120 /// An iterator over substrings of the given string slice, separated by
1121 /// characters matched by a pattern.
1123 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1126 /// Equivalent to [`split`], except that the trailing substring
1127 /// is skipped if empty.
1129 /// [`split`]: #method.split
1131 /// This method can be used for string data that is _terminated_,
1132 /// rather than _separated_ by a pattern.
1134 /// # Iterator behavior
1136 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1137 /// allows a reverse search and forward/reverse search yields the same
1138 /// elements. This is true for, eg, [`char`] but not for `&str`.
1140 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1141 /// [`char`]: primitive.char.html
1143 /// If the pattern allows a reverse search but its results might differ
1144 /// from a forward search, the [`rsplit_terminator`] method can be used.
1146 /// [`rsplit_terminator`]: #method.rsplit_terminator
1153 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1154 /// assert_eq!(v, ["A", "B"]);
1156 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1157 /// assert_eq!(v, ["A", "", "B", ""]);
1159 #[stable(feature = "rust1", since = "1.0.0")]
1161 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1162 core_str::StrExt::split_terminator(self, pat)
1165 /// An iterator over substrings of `self`, separated by characters
1166 /// matched by a pattern and yielded in reverse order.
1168 /// The pattern can be a simple `&str`, [`char`], or a closure that
1169 /// determines the split.
1170 /// Additional libraries might provide more complex patterns like
1171 /// regular expressions.
1173 /// [`char`]: primitive.char.html
1175 /// Equivalent to [`split`], except that the trailing substring is
1176 /// skipped if empty.
1178 /// [`split`]: #method.split
1180 /// This method can be used for string data that is _terminated_,
1181 /// rather than _separated_ by a pattern.
1183 /// # Iterator behavior
1185 /// The returned iterator requires that the pattern supports a
1186 /// reverse search, and it will be double ended if a forward/reverse
1187 /// search yields the same elements.
1189 /// For iterating from the front, the [`split_terminator`] method can be
1192 /// [`split_terminator`]: #method.split_terminator
1197 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1198 /// assert_eq!(v, ["B", "A"]);
1200 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1201 /// assert_eq!(v, ["", "B", "", "A"]);
1203 #[stable(feature = "rust1", since = "1.0.0")]
1205 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1206 where P::Searcher: ReverseSearcher<'a>
1208 core_str::StrExt::rsplit_terminator(self, pat)
1211 /// An iterator over substrings of the given string slice, separated by a
1212 /// pattern, restricted to returning at most `n` items.
1214 /// If `n` substrings are returned, the last substring (the `n`th substring)
1215 /// will contain the remainder of the string.
1217 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1220 /// [`char`]: primitive.char.html
1222 /// # Iterator behavior
1224 /// The returned iterator will not be double ended, because it is
1225 /// not efficient to support.
1227 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1230 /// [`rsplitn`]: #method.rsplitn
1234 /// Simple patterns:
1237 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1238 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1240 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1241 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1243 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1244 /// assert_eq!(v, ["abcXdef"]);
1246 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1247 /// assert_eq!(v, [""]);
1250 /// A more complex pattern, using a closure:
1253 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1254 /// assert_eq!(v, ["abc", "defXghi"]);
1256 #[stable(feature = "rust1", since = "1.0.0")]
1258 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1259 core_str::StrExt::splitn(self, n, pat)
1262 /// An iterator over substrings of this string slice, separated by a
1263 /// pattern, starting from the end of the string, restricted to returning
1264 /// at most `n` items.
1266 /// If `n` substrings are returned, the last substring (the `n`th substring)
1267 /// will contain the remainder of the string.
1269 /// The pattern can be a `&str`, [`char`], or a closure that
1270 /// determines the split.
1272 /// [`char`]: primitive.char.html
1274 /// # Iterator behavior
1276 /// The returned iterator will not be double ended, because it is not
1277 /// efficient to support.
1279 /// For splitting from the front, the [`splitn`] method can be used.
1281 /// [`splitn`]: #method.splitn
1285 /// Simple patterns:
1288 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1289 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1291 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1292 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1294 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1295 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1298 /// A more complex pattern, using a closure:
1301 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1302 /// assert_eq!(v, ["ghi", "abc1def"]);
1304 #[stable(feature = "rust1", since = "1.0.0")]
1306 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1307 where P::Searcher: ReverseSearcher<'a>
1309 core_str::StrExt::rsplitn(self, n, pat)
1312 /// An iterator over the matches of a pattern within the given string
1315 /// The pattern can be a `&str`, [`char`], or a closure that
1316 /// determines if a character matches.
1318 /// [`char`]: primitive.char.html
1320 /// # Iterator behavior
1322 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1323 /// allows a reverse search and forward/reverse search yields the same
1324 /// elements. This is true for, eg, [`char`] but not for `&str`.
1326 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1327 /// [`char`]: primitive.char.html
1329 /// If the pattern allows a reverse search but its results might differ
1330 /// from a forward search, the [`rmatches`] method can be used.
1332 /// [`rmatches`]: #method.rmatches
1339 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1340 /// assert_eq!(v, ["abc", "abc", "abc"]);
1342 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1343 /// assert_eq!(v, ["1", "2", "3"]);
1345 #[stable(feature = "str_matches", since = "1.2.0")]
1347 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1348 core_str::StrExt::matches(self, pat)
1351 /// An iterator over the matches of a pattern within this string slice,
1352 /// yielded in reverse order.
1354 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1355 /// a character matches.
1357 /// [`char`]: primitive.char.html
1359 /// # Iterator behavior
1361 /// The returned iterator requires that the pattern supports a reverse
1362 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1363 /// search yields the same elements.
1365 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1367 /// For iterating from the front, the [`matches`] method can be used.
1369 /// [`matches`]: #method.matches
1376 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1377 /// assert_eq!(v, ["abc", "abc", "abc"]);
1379 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1380 /// assert_eq!(v, ["3", "2", "1"]);
1382 #[stable(feature = "str_matches", since = "1.2.0")]
1384 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1385 where P::Searcher: ReverseSearcher<'a>
1387 core_str::StrExt::rmatches(self, pat)
1390 /// An iterator over the disjoint matches of a pattern within this string
1391 /// slice as well as the index that the match starts at.
1393 /// For matches of `pat` within `self` that overlap, only the indices
1394 /// corresponding to the first match are returned.
1396 /// The pattern can be a `&str`, [`char`], or a closure that determines
1397 /// if a character matches.
1399 /// [`char`]: primitive.char.html
1401 /// # Iterator behavior
1403 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1404 /// allows a reverse search and forward/reverse search yields the same
1405 /// elements. This is true for, eg, [`char`] but not for `&str`.
1407 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1409 /// If the pattern allows a reverse search but its results might differ
1410 /// from a forward search, the [`rmatch_indices`] method can be used.
1412 /// [`rmatch_indices`]: #method.rmatch_indices
1419 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1420 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1422 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1423 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1425 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1426 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1428 #[stable(feature = "str_match_indices", since = "1.5.0")]
1430 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1431 core_str::StrExt::match_indices(self, pat)
1434 /// An iterator over the disjoint matches of a pattern within `self`,
1435 /// yielded in reverse order along with the index of the match.
1437 /// For matches of `pat` within `self` that overlap, only the indices
1438 /// corresponding to the last match are returned.
1440 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1441 /// character matches.
1443 /// [`char`]: primitive.char.html
1445 /// # Iterator behavior
1447 /// The returned iterator requires that the pattern supports a reverse
1448 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1449 /// search yields the same elements.
1451 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1453 /// For iterating from the front, the [`match_indices`] method can be used.
1455 /// [`match_indices`]: #method.match_indices
1462 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1463 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1465 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1466 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1468 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1469 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1471 #[stable(feature = "str_match_indices", since = "1.5.0")]
1473 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1474 where P::Searcher: ReverseSearcher<'a>
1476 core_str::StrExt::rmatch_indices(self, pat)
1479 /// Returns a string slice with leading and trailing whitespace removed.
1481 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1482 /// Core Property `White_Space`.
1489 /// let s = " Hello\tworld\t";
1491 /// assert_eq!("Hello\tworld", s.trim());
1493 #[stable(feature = "rust1", since = "1.0.0")]
1494 pub fn trim(&self) -> &str {
1495 UnicodeStr::trim(self)
1498 /// Returns a string slice with leading whitespace removed.
1500 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1501 /// Core Property `White_Space`.
1503 /// # Text directionality
1505 /// A string is a sequence of bytes. 'Left' in this context means the first
1506 /// position of that byte string; for a language like Arabic or Hebrew
1507 /// which are 'right to left' rather than 'left to right', this will be
1508 /// the _right_ side, not the left.
1515 /// let s = " Hello\tworld\t";
1517 /// assert_eq!("Hello\tworld\t", s.trim_left());
1523 /// let s = " English";
1524 /// assert!(Some('E') == s.trim_left().chars().next());
1526 /// let s = " עברית";
1527 /// assert!(Some('ע') == s.trim_left().chars().next());
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 pub fn trim_left(&self) -> &str {
1531 UnicodeStr::trim_left(self)
1534 /// Returns a string slice with trailing whitespace removed.
1536 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1537 /// Core Property `White_Space`.
1539 /// # Text directionality
1541 /// A string is a sequence of bytes. 'Right' in this context means the last
1542 /// position of that byte string; for a language like Arabic or Hebrew
1543 /// which are 'right to left' rather than 'left to right', this will be
1544 /// the _left_ side, not the right.
1551 /// let s = " Hello\tworld\t";
1553 /// assert_eq!(" Hello\tworld", s.trim_right());
1559 /// let s = "English ";
1560 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1562 /// let s = "עברית ";
1563 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 pub fn trim_right(&self) -> &str {
1567 UnicodeStr::trim_right(self)
1570 /// Returns a string slice with all prefixes and suffixes that match a
1571 /// pattern repeatedly removed.
1573 /// The pattern can be a [`char`] or a closure that determines if a
1574 /// character matches.
1576 /// [`char`]: primitive.char.html
1580 /// Simple patterns:
1583 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1584 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1586 /// let x: &[_] = &['1', '2'];
1587 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1590 /// A more complex pattern, using a closure:
1593 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1597 where P::Searcher: DoubleEndedSearcher<'a>
1599 core_str::StrExt::trim_matches(self, pat)
1602 /// Returns a string slice with all prefixes that match a pattern
1603 /// repeatedly removed.
1605 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1606 /// a character matches.
1608 /// [`char`]: primitive.char.html
1610 /// # Text directionality
1612 /// A string is a sequence of bytes. 'Left' in this context means the first
1613 /// position of that byte string; for a language like Arabic or Hebrew
1614 /// which are 'right to left' rather than 'left to right', this will be
1615 /// the _right_ side, not the left.
1622 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1623 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1625 /// let x: &[_] = &['1', '2'];
1626 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1630 core_str::StrExt::trim_left_matches(self, pat)
1633 /// Returns a string slice with all suffixes that match a pattern
1634 /// repeatedly removed.
1636 /// The pattern can be a `&str`, [`char`], or a closure that
1637 /// determines if a character matches.
1639 /// [`char`]: primitive.char.html
1641 /// # Text directionality
1643 /// A string is a sequence of bytes. 'Right' in this context means the last
1644 /// position of that byte string; for a language like Arabic or Hebrew
1645 /// which are 'right to left' rather than 'left to right', this will be
1646 /// the _left_ side, not the right.
1650 /// Simple patterns:
1653 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1654 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1656 /// let x: &[_] = &['1', '2'];
1657 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1660 /// A more complex pattern, using a closure:
1663 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1667 where P::Searcher: ReverseSearcher<'a>
1669 core_str::StrExt::trim_right_matches(self, pat)
1672 /// Parses this string slice into another type.
1674 /// Because `parse` is so general, it can cause problems with type
1675 /// inference. As such, `parse` is one of the few times you'll see
1676 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1677 /// helps the inference algorithm understand specifically which type
1678 /// you're trying to parse into.
1680 /// `parse` can parse any type that implements the [`FromStr`] trait.
1682 /// [`FromStr`]: str/trait.FromStr.html
1686 /// Will return [`Err`] if it's not possible to parse this string slice into
1687 /// the desired type.
1689 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1696 /// let four: u32 = "4".parse().unwrap();
1698 /// assert_eq!(4, four);
1701 /// Using the 'turbofish' instead of annotating `four`:
1704 /// let four = "4".parse::<u32>();
1706 /// assert_eq!(Ok(4), four);
1709 /// Failing to parse:
1712 /// let nope = "j".parse::<u32>();
1714 /// assert!(nope.is_err());
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1719 core_str::StrExt::parse(self)
1722 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
1723 #[unstable(feature = "str_box_extras", issue = "41119")]
1724 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
1728 /// Replaces all matches of a pattern with another string.
1730 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1731 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1732 /// replaces them with the replacement string slice.
1734 /// [`String`]: string/struct.String.html
1741 /// let s = "this is old";
1743 /// assert_eq!("this is new", s.replace("old", "new"));
1746 /// When the pattern doesn't match:
1749 /// let s = "this is old";
1750 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1752 #[stable(feature = "rust1", since = "1.0.0")]
1754 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1755 let mut result = String::new();
1756 let mut last_end = 0;
1757 for (start, part) in self.match_indices(from) {
1758 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1759 result.push_str(to);
1760 last_end = start + part.len();
1762 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1766 /// Replaces first N matches of a pattern with another string.
1768 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1769 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1770 /// replaces them with the replacement string slice at most `count` times.
1772 /// [`String`]: string/struct.String.html
1779 /// let s = "foo foo 123 foo";
1780 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1781 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1782 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1785 /// When the pattern doesn't match:
1788 /// let s = "this is old";
1789 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1791 #[stable(feature = "str_replacen", since = "1.16.0")]
1792 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1793 // Hope to reduce the times of re-allocation
1794 let mut result = String::with_capacity(32);
1795 let mut last_end = 0;
1796 for (start, part) in self.match_indices(pat).take(count) {
1797 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1798 result.push_str(to);
1799 last_end = start + part.len();
1801 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1805 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1807 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1810 /// Since some characters can expand into multiple characters when changing
1811 /// the case, this function returns a [`String`] instead of modifying the
1812 /// parameter in-place.
1814 /// [`String`]: string/struct.String.html
1821 /// let s = "HELLO";
1823 /// assert_eq!("hello", s.to_lowercase());
1826 /// A tricky example, with sigma:
1829 /// let sigma = "Σ";
1831 /// assert_eq!("σ", sigma.to_lowercase());
1833 /// // but at the end of a word, it's ς, not σ:
1834 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1836 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1839 /// Languages without case are not changed:
1842 /// let new_year = "农历新年";
1844 /// assert_eq!(new_year, new_year.to_lowercase());
1846 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1847 pub fn to_lowercase(&self) -> String {
1848 let mut s = String::with_capacity(self.len());
1849 for (i, c) in self[..].char_indices() {
1851 // Σ maps to σ, except at the end of a word where it maps to ς.
1852 // This is the only conditional (contextual) but language-independent mapping
1853 // in `SpecialCasing.txt`,
1854 // so hard-code it rather than have a generic "condition" mechanism.
1855 // See https://github.com/rust-lang/rust/issues/26035
1856 map_uppercase_sigma(self, i, &mut s)
1858 s.extend(c.to_lowercase());
1863 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1864 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1865 // for the definition of `Final_Sigma`.
1866 debug_assert!('Σ'.len_utf8() == 2);
1867 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1868 !case_ignoreable_then_cased(from[i + 2..].chars());
1869 to.push_str(if is_word_final { "ς" } else { "σ" });
1872 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1873 use std_unicode::derived_property::{Cased, Case_Ignorable};
1874 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1875 Some(c) => Cased(c),
1881 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1883 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1886 /// Since some characters can expand into multiple characters when changing
1887 /// the case, this function returns a [`String`] instead of modifying the
1888 /// parameter in-place.
1890 /// [`String`]: string/struct.String.html
1897 /// let s = "hello";
1899 /// assert_eq!("HELLO", s.to_uppercase());
1902 /// Scripts without case are not changed:
1905 /// let new_year = "农历新年";
1907 /// assert_eq!(new_year, new_year.to_uppercase());
1909 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1910 pub fn to_uppercase(&self) -> String {
1911 let mut s = String::with_capacity(self.len());
1912 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1916 /// Escapes each char in `s` with [`char::escape_debug`].
1918 /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
1919 #[unstable(feature = "str_escape",
1920 reason = "return type may change to be an iterator",
1922 pub fn escape_debug(&self) -> String {
1923 self.chars().flat_map(|c| c.escape_debug()).collect()
1926 /// Escapes each char in `s` with [`char::escape_default`].
1928 /// [`char::escape_default`]: primitive.char.html#method.escape_default
1929 #[unstable(feature = "str_escape",
1930 reason = "return type may change to be an iterator",
1932 pub fn escape_default(&self) -> String {
1933 self.chars().flat_map(|c| c.escape_default()).collect()
1936 /// Escapes each char in `s` with [`char::escape_unicode`].
1938 /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
1939 #[unstable(feature = "str_escape",
1940 reason = "return type may change to be an iterator",
1942 pub fn escape_unicode(&self) -> String {
1943 self.chars().flat_map(|c| c.escape_unicode()).collect()
1946 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
1948 /// [`String`]: string/struct.String.html
1949 /// [`Box<str>`]: boxed/struct.Box.html
1956 /// let string = String::from("birthday gift");
1957 /// let boxed_str = string.clone().into_boxed_str();
1959 /// assert_eq!(boxed_str.into_string(), string);
1961 #[stable(feature = "box_str", since = "1.4.0")]
1962 pub fn into_string(self: Box<str>) -> String {
1964 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1965 String::from_utf8_unchecked(slice.into_vec())
1969 /// Create a [`String`] by repeating a string `n` times.
1971 /// [`String`]: string/struct.String.html
1978 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
1980 #[stable(feature = "repeat_str", since = "1.16.0")]
1981 pub fn repeat(&self, n: usize) -> String {
1982 let mut s = String::with_capacity(self.len() * n);
1983 s.extend((0..n).map(|_| self));