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")]
816 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
817 core_str::StrExt::contains(self, pat)
820 /// Returns `true` if the given pattern matches a prefix of this
823 /// Returns `false` if it does not.
830 /// let bananas = "bananas";
832 /// assert!(bananas.starts_with("bana"));
833 /// assert!(!bananas.starts_with("nana"));
835 #[stable(feature = "rust1", since = "1.0.0")]
836 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
837 core_str::StrExt::starts_with(self, pat)
840 /// Returns `true` if the given pattern matches a suffix of this
843 /// Returns `false` if it does not.
850 /// let bananas = "bananas";
852 /// assert!(bananas.ends_with("anas"));
853 /// assert!(!bananas.ends_with("nana"));
855 #[stable(feature = "rust1", since = "1.0.0")]
856 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
857 where P::Searcher: ReverseSearcher<'a>
859 core_str::StrExt::ends_with(self, pat)
862 /// Returns the byte index of the first character of this string slice that
863 /// matches the pattern.
865 /// Returns [`None`] if the pattern doesn't match.
867 /// The pattern can be a `&str`, [`char`], or a closure that determines if
868 /// a character matches.
870 /// [`char`]: primitive.char.html
871 /// [`None`]: option/enum.Option.html#variant.None
878 /// let s = "Löwe 老虎 Léopard";
880 /// assert_eq!(s.find('L'), Some(0));
881 /// assert_eq!(s.find('é'), Some(14));
882 /// assert_eq!(s.find("Léopard"), Some(13));
885 /// More complex patterns with closures:
888 /// let s = "Löwe 老虎 Léopard";
890 /// assert_eq!(s.find(char::is_whitespace), Some(5));
891 /// assert_eq!(s.find(char::is_lowercase), Some(1));
894 /// Not finding the pattern:
897 /// let s = "Löwe 老虎 Léopard";
898 /// let x: &[_] = &['1', '2'];
900 /// assert_eq!(s.find(x), None);
902 #[stable(feature = "rust1", since = "1.0.0")]
903 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
904 core_str::StrExt::find(self, pat)
907 /// Returns the byte index of the last character of this string slice that
908 /// matches the pattern.
910 /// Returns [`None`] if the pattern doesn't match.
912 /// The pattern can be a `&str`, [`char`], or a closure that determines if
913 /// a character matches.
915 /// [`char`]: primitive.char.html
916 /// [`None`]: option/enum.Option.html#variant.None
923 /// let s = "Löwe 老虎 Léopard";
925 /// assert_eq!(s.rfind('L'), Some(13));
926 /// assert_eq!(s.rfind('é'), Some(14));
929 /// More complex patterns with closures:
932 /// let s = "Löwe 老虎 Léopard";
934 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
935 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
938 /// Not finding the pattern:
941 /// let s = "Löwe 老虎 Léopard";
942 /// let x: &[_] = &['1', '2'];
944 /// assert_eq!(s.rfind(x), None);
946 #[stable(feature = "rust1", since = "1.0.0")]
947 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
948 where P::Searcher: ReverseSearcher<'a>
950 core_str::StrExt::rfind(self, pat)
953 /// An iterator over substrings of this string slice, separated by
954 /// characters matched by a pattern.
956 /// The pattern can be a `&str`, [`char`], or a closure that determines the
959 /// # Iterator behavior
961 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
962 /// allows a reverse search and forward/reverse search yields the same
963 /// elements. This is true for, eg, [`char`] but not for `&str`.
965 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
967 /// If the pattern allows a reverse search but its results might differ
968 /// from a forward search, the [`rsplit`] method can be used.
970 /// [`char`]: primitive.char.html
971 /// [`rsplit`]: #method.rsplit
978 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
979 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
981 /// let v: Vec<&str> = "".split('X').collect();
982 /// assert_eq!(v, [""]);
984 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
985 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
987 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
988 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
990 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
991 /// assert_eq!(v, ["abc", "def", "ghi"]);
993 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
994 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
997 /// A more complex pattern, using a closure:
1000 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1001 /// assert_eq!(v, ["abc", "def", "ghi"]);
1004 /// If a string contains multiple contiguous separators, you will end up
1005 /// with empty strings in the output:
1008 /// let x = "||||a||b|c".to_string();
1009 /// let d: Vec<_> = x.split('|').collect();
1011 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1014 /// Contiguous separators are separated by the empty string.
1017 /// let x = "(///)".to_string();
1018 /// let d: Vec<_> = x.split('/').collect();;
1020 /// assert_eq!(d, &["(", "", "", ")"]);
1023 /// Separators at the start or end of a string are neighbored
1024 /// by empty strings.
1027 /// let d: Vec<_> = "010".split("0").collect();
1028 /// assert_eq!(d, &["", "1", ""]);
1031 /// When the empty string is used as a separator, it separates
1032 /// every character in the string, along with the beginning
1033 /// and end of the string.
1036 /// let f: Vec<_> = "rust".split("").collect();
1037 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1040 /// Contiguous separators can lead to possibly surprising behavior
1041 /// when whitespace is used as the separator. This code is correct:
1044 /// let x = " a b c".to_string();
1045 /// let d: Vec<_> = x.split(' ').collect();
1047 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1050 /// It does _not_ give you:
1053 /// assert_eq!(d, &["a", "b", "c"]);
1056 /// Use [`split_whitespace`] for this behavior.
1058 /// [`split_whitespace`]: #method.split_whitespace
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1061 core_str::StrExt::split(self, pat)
1064 /// An iterator over substrings of the given string slice, separated by
1065 /// characters matched by a pattern and yielded in reverse order.
1067 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1070 /// [`char`]: primitive.char.html
1072 /// # Iterator behavior
1074 /// The returned iterator requires that the pattern supports a reverse
1075 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1076 /// search yields the same elements.
1078 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1080 /// For iterating from the front, the [`split`] method can be used.
1082 /// [`split`]: #method.split
1086 /// Simple patterns:
1089 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1090 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1092 /// let v: Vec<&str> = "".rsplit('X').collect();
1093 /// assert_eq!(v, [""]);
1095 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1096 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1098 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1099 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1102 /// A more complex pattern, using a closure:
1105 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1106 /// assert_eq!(v, ["ghi", "def", "abc"]);
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1110 where P::Searcher: ReverseSearcher<'a>
1112 core_str::StrExt::rsplit(self, pat)
1115 /// An iterator over substrings of the given string slice, separated by
1116 /// characters matched by a pattern.
1118 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1121 /// Equivalent to [`split`], except that the trailing substring
1122 /// is skipped if empty.
1124 /// [`split`]: #method.split
1126 /// This method can be used for string data that is _terminated_,
1127 /// rather than _separated_ by a pattern.
1129 /// # Iterator behavior
1131 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1132 /// allows a reverse search and forward/reverse search yields the same
1133 /// elements. This is true for, eg, [`char`] but not for `&str`.
1135 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1136 /// [`char`]: primitive.char.html
1138 /// If the pattern allows a reverse search but its results might differ
1139 /// from a forward search, the [`rsplit_terminator`] method can be used.
1141 /// [`rsplit_terminator`]: #method.rsplit_terminator
1148 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1149 /// assert_eq!(v, ["A", "B"]);
1151 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1152 /// assert_eq!(v, ["A", "", "B", ""]);
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1156 core_str::StrExt::split_terminator(self, pat)
1159 /// An iterator over substrings of `self`, separated by characters
1160 /// matched by a pattern and yielded in reverse order.
1162 /// The pattern can be a simple `&str`, [`char`], or a closure that
1163 /// determines the split.
1164 /// Additional libraries might provide more complex patterns like
1165 /// regular expressions.
1167 /// [`char`]: primitive.char.html
1169 /// Equivalent to [`split`], except that the trailing substring is
1170 /// skipped if empty.
1172 /// [`split`]: #method.split
1174 /// This method can be used for string data that is _terminated_,
1175 /// rather than _separated_ by a pattern.
1177 /// # Iterator behavior
1179 /// The returned iterator requires that the pattern supports a
1180 /// reverse search, and it will be double ended if a forward/reverse
1181 /// search yields the same elements.
1183 /// For iterating from the front, the [`split_terminator`] method can be
1186 /// [`split_terminator`]: #method.split_terminator
1191 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1192 /// assert_eq!(v, ["B", "A"]);
1194 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1195 /// assert_eq!(v, ["", "B", "", "A"]);
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1199 where P::Searcher: ReverseSearcher<'a>
1201 core_str::StrExt::rsplit_terminator(self, pat)
1204 /// An iterator over substrings of the given string slice, separated by a
1205 /// pattern, restricted to returning at most `n` items.
1207 /// If `n` substrings are returned, the last substring (the `n`th substring)
1208 /// will contain the remainder of the string.
1210 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1213 /// [`char`]: primitive.char.html
1215 /// # Iterator behavior
1217 /// The returned iterator will not be double ended, because it is
1218 /// not efficient to support.
1220 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1223 /// [`rsplitn`]: #method.rsplitn
1227 /// Simple patterns:
1230 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1231 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1233 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1234 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1236 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1237 /// assert_eq!(v, ["abcXdef"]);
1239 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1240 /// assert_eq!(v, [""]);
1243 /// A more complex pattern, using a closure:
1246 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1247 /// assert_eq!(v, ["abc", "defXghi"]);
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1251 core_str::StrExt::splitn(self, n, pat)
1254 /// An iterator over substrings of this string slice, separated by a
1255 /// pattern, starting from the end of the string, restricted to returning
1256 /// at most `n` items.
1258 /// If `n` substrings are returned, the last substring (the `n`th substring)
1259 /// will contain the remainder of the string.
1261 /// The pattern can be a `&str`, [`char`], or a closure that
1262 /// determines the split.
1264 /// [`char`]: primitive.char.html
1266 /// # Iterator behavior
1268 /// The returned iterator will not be double ended, because it is not
1269 /// efficient to support.
1271 /// For splitting from the front, the [`splitn`] method can be used.
1273 /// [`splitn`]: #method.splitn
1277 /// Simple patterns:
1280 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1281 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1283 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1284 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1286 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1287 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1290 /// A more complex pattern, using a closure:
1293 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1294 /// assert_eq!(v, ["ghi", "abc1def"]);
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1298 where P::Searcher: ReverseSearcher<'a>
1300 core_str::StrExt::rsplitn(self, n, pat)
1303 /// An iterator over the matches of a pattern within the given string
1306 /// The pattern can be a `&str`, [`char`], or a closure that
1307 /// determines if a character matches.
1309 /// [`char`]: primitive.char.html
1311 /// # Iterator behavior
1313 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1314 /// allows a reverse search and forward/reverse search yields the same
1315 /// elements. This is true for, eg, [`char`] but not for `&str`.
1317 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1318 /// [`char`]: primitive.char.html
1320 /// If the pattern allows a reverse search but its results might differ
1321 /// from a forward search, the [`rmatches`] method can be used.
1323 /// [`rmatches`]: #method.rmatches
1330 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1331 /// assert_eq!(v, ["abc", "abc", "abc"]);
1333 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1334 /// assert_eq!(v, ["1", "2", "3"]);
1336 #[stable(feature = "str_matches", since = "1.2.0")]
1337 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1338 core_str::StrExt::matches(self, pat)
1341 /// An iterator over the matches of a pattern within this string slice,
1342 /// yielded in reverse order.
1344 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1345 /// a character matches.
1347 /// [`char`]: primitive.char.html
1349 /// # Iterator behavior
1351 /// The returned iterator requires that the pattern supports a reverse
1352 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1353 /// search yields the same elements.
1355 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1357 /// For iterating from the front, the [`matches`] method can be used.
1359 /// [`matches`]: #method.matches
1366 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1367 /// assert_eq!(v, ["abc", "abc", "abc"]);
1369 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1370 /// assert_eq!(v, ["3", "2", "1"]);
1372 #[stable(feature = "str_matches", since = "1.2.0")]
1373 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1374 where P::Searcher: ReverseSearcher<'a>
1376 core_str::StrExt::rmatches(self, pat)
1379 /// An iterator over the disjoint matches of a pattern within this string
1380 /// slice as well as the index that the match starts at.
1382 /// For matches of `pat` within `self` that overlap, only the indices
1383 /// corresponding to the first match are returned.
1385 /// The pattern can be a `&str`, [`char`], or a closure that determines
1386 /// if a character matches.
1388 /// [`char`]: primitive.char.html
1390 /// # Iterator behavior
1392 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1393 /// allows a reverse search and forward/reverse search yields the same
1394 /// elements. This is true for, eg, [`char`] but not for `&str`.
1396 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1398 /// If the pattern allows a reverse search but its results might differ
1399 /// from a forward search, the [`rmatch_indices`] method can be used.
1401 /// [`rmatch_indices`]: #method.rmatch_indices
1408 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1409 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1411 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1412 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1414 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1415 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1417 #[stable(feature = "str_match_indices", since = "1.5.0")]
1418 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1419 core_str::StrExt::match_indices(self, pat)
1422 /// An iterator over the disjoint matches of a pattern within `self`,
1423 /// yielded in reverse order along with the index of the match.
1425 /// For matches of `pat` within `self` that overlap, only the indices
1426 /// corresponding to the last match are returned.
1428 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1429 /// character matches.
1431 /// [`char`]: primitive.char.html
1433 /// # Iterator behavior
1435 /// The returned iterator requires that the pattern supports a reverse
1436 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1437 /// search yields the same elements.
1439 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1441 /// For iterating from the front, the [`match_indices`] method can be used.
1443 /// [`match_indices`]: #method.match_indices
1450 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1451 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1453 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1454 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1456 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1457 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1459 #[stable(feature = "str_match_indices", since = "1.5.0")]
1460 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1461 where P::Searcher: ReverseSearcher<'a>
1463 core_str::StrExt::rmatch_indices(self, pat)
1466 /// Returns a string slice with leading and trailing whitespace removed.
1468 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1469 /// Core Property `White_Space`.
1476 /// let s = " Hello\tworld\t";
1478 /// assert_eq!("Hello\tworld", s.trim());
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 pub fn trim(&self) -> &str {
1482 UnicodeStr::trim(self)
1485 /// Returns a string slice with leading whitespace removed.
1487 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1488 /// Core Property `White_Space`.
1490 /// # Text directionality
1492 /// A string is a sequence of bytes. 'Left' in this context means the first
1493 /// position of that byte string; for a language like Arabic or Hebrew
1494 /// which are 'right to left' rather than 'left to right', this will be
1495 /// the _right_ side, not the left.
1502 /// let s = " Hello\tworld\t";
1504 /// assert_eq!("Hello\tworld\t", s.trim_left());
1510 /// let s = " English";
1511 /// assert!(Some('E') == s.trim_left().chars().next());
1513 /// let s = " עברית";
1514 /// assert!(Some('ע') == s.trim_left().chars().next());
1516 #[stable(feature = "rust1", since = "1.0.0")]
1517 pub fn trim_left(&self) -> &str {
1518 UnicodeStr::trim_left(self)
1521 /// Returns a string slice with trailing whitespace removed.
1523 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1524 /// Core Property `White_Space`.
1526 /// # Text directionality
1528 /// A string is a sequence of bytes. 'Right' in this context means the last
1529 /// position of that byte string; for a language like Arabic or Hebrew
1530 /// which are 'right to left' rather than 'left to right', this will be
1531 /// the _left_ side, not the right.
1538 /// let s = " Hello\tworld\t";
1540 /// assert_eq!(" Hello\tworld", s.trim_right());
1546 /// let s = "English ";
1547 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1549 /// let s = "עברית ";
1550 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 pub fn trim_right(&self) -> &str {
1554 UnicodeStr::trim_right(self)
1557 /// Returns a string slice with all prefixes and suffixes that match a
1558 /// pattern repeatedly removed.
1560 /// The pattern can be a [`char`] or a closure that determines if a
1561 /// character matches.
1563 /// [`char`]: primitive.char.html
1567 /// Simple patterns:
1570 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1571 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1573 /// let x: &[_] = &['1', '2'];
1574 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1577 /// A more complex pattern, using a closure:
1580 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1584 where P::Searcher: DoubleEndedSearcher<'a>
1586 core_str::StrExt::trim_matches(self, pat)
1589 /// Returns a string slice with all prefixes that match a pattern
1590 /// repeatedly removed.
1592 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1593 /// a character matches.
1595 /// [`char`]: primitive.char.html
1597 /// # Text directionality
1599 /// A string is a sequence of bytes. 'Left' in this context means the first
1600 /// position of that byte string; for a language like Arabic or Hebrew
1601 /// which are 'right to left' rather than 'left to right', this will be
1602 /// the _right_ side, not the left.
1609 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1610 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1612 /// let x: &[_] = &['1', '2'];
1613 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1617 core_str::StrExt::trim_left_matches(self, pat)
1620 /// Returns a string slice with all suffixes that match a pattern
1621 /// repeatedly removed.
1623 /// The pattern can be a `&str`, [`char`], or a closure that
1624 /// determines if a character matches.
1626 /// [`char`]: primitive.char.html
1628 /// # Text directionality
1630 /// A string is a sequence of bytes. 'Right' in this context means the last
1631 /// position of that byte string; for a language like Arabic or Hebrew
1632 /// which are 'right to left' rather than 'left to right', this will be
1633 /// the _left_ side, not the right.
1637 /// Simple patterns:
1640 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1641 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1643 /// let x: &[_] = &['1', '2'];
1644 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1647 /// A more complex pattern, using a closure:
1650 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1652 #[stable(feature = "rust1", since = "1.0.0")]
1653 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1654 where P::Searcher: ReverseSearcher<'a>
1656 core_str::StrExt::trim_right_matches(self, pat)
1659 /// Parses this string slice into another type.
1661 /// Because `parse` is so general, it can cause problems with type
1662 /// inference. As such, `parse` is one of the few times you'll see
1663 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1664 /// helps the inference algorithm understand specifically which type
1665 /// you're trying to parse into.
1667 /// `parse` can parse any type that implements the [`FromStr`] trait.
1669 /// [`FromStr`]: str/trait.FromStr.html
1673 /// Will return [`Err`] if it's not possible to parse this string slice into
1674 /// the desired type.
1676 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1683 /// let four: u32 = "4".parse().unwrap();
1685 /// assert_eq!(4, four);
1688 /// Using the 'turbofish' instead of annotating `four`:
1691 /// let four = "4".parse::<u32>();
1693 /// assert_eq!(Ok(4), four);
1696 /// Failing to parse:
1699 /// let nope = "j".parse::<u32>();
1701 /// assert!(nope.is_err());
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1706 core_str::StrExt::parse(self)
1709 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
1710 #[unstable(feature = "str_box_extras", issue = "41119")]
1711 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
1715 /// Replaces all matches of a pattern with another string.
1717 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1718 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1719 /// replaces them with the replacement string slice.
1721 /// [`String`]: string/struct.String.html
1728 /// let s = "this is old";
1730 /// assert_eq!("this is new", s.replace("old", "new"));
1733 /// When the pattern doesn't match:
1736 /// let s = "this is old";
1737 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1741 let mut result = String::new();
1742 let mut last_end = 0;
1743 for (start, part) in self.match_indices(from) {
1744 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1745 result.push_str(to);
1746 last_end = start + part.len();
1748 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1752 /// Replaces first N matches of a pattern with another string.
1754 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1755 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1756 /// replaces them with the replacement string slice at most `count` times.
1758 /// [`String`]: string/struct.String.html
1765 /// let s = "foo foo 123 foo";
1766 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1767 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1768 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1771 /// When the pattern doesn't match:
1774 /// let s = "this is old";
1775 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1777 #[stable(feature = "str_replacen", since = "1.16.0")]
1778 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1779 // Hope to reduce the times of re-allocation
1780 let mut result = String::with_capacity(32);
1781 let mut last_end = 0;
1782 for (start, part) in self.match_indices(pat).take(count) {
1783 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1784 result.push_str(to);
1785 last_end = start + part.len();
1787 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1791 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1793 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1796 /// Since some characters can expand into multiple characters when changing
1797 /// the case, this function returns a [`String`] instead of modifying the
1798 /// parameter in-place.
1800 /// [`String`]: string/struct.String.html
1807 /// let s = "HELLO";
1809 /// assert_eq!("hello", s.to_lowercase());
1812 /// A tricky example, with sigma:
1815 /// let sigma = "Σ";
1817 /// assert_eq!("σ", sigma.to_lowercase());
1819 /// // but at the end of a word, it's ς, not σ:
1820 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1822 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1825 /// Languages without case are not changed:
1828 /// let new_year = "农历新年";
1830 /// assert_eq!(new_year, new_year.to_lowercase());
1832 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1833 pub fn to_lowercase(&self) -> String {
1834 let mut s = String::with_capacity(self.len());
1835 for (i, c) in self[..].char_indices() {
1837 // Σ maps to σ, except at the end of a word where it maps to ς.
1838 // This is the only conditional (contextual) but language-independent mapping
1839 // in `SpecialCasing.txt`,
1840 // so hard-code it rather than have a generic "condition" mechanism.
1841 // See https://github.com/rust-lang/rust/issues/26035
1842 map_uppercase_sigma(self, i, &mut s)
1844 s.extend(c.to_lowercase());
1849 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1850 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1851 // for the definition of `Final_Sigma`.
1852 debug_assert!('Σ'.len_utf8() == 2);
1853 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1854 !case_ignoreable_then_cased(from[i + 2..].chars());
1855 to.push_str(if is_word_final { "ς" } else { "σ" });
1858 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1859 use std_unicode::derived_property::{Cased, Case_Ignorable};
1860 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1861 Some(c) => Cased(c),
1867 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1869 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1872 /// Since some characters can expand into multiple characters when changing
1873 /// the case, this function returns a [`String`] instead of modifying the
1874 /// parameter in-place.
1876 /// [`String`]: string/struct.String.html
1883 /// let s = "hello";
1885 /// assert_eq!("HELLO", s.to_uppercase());
1888 /// Scripts without case are not changed:
1891 /// let new_year = "农历新年";
1893 /// assert_eq!(new_year, new_year.to_uppercase());
1895 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1896 pub fn to_uppercase(&self) -> String {
1897 let mut s = String::with_capacity(self.len());
1898 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1902 /// Escapes each char in `s` with [`char::escape_debug`].
1904 /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
1905 #[unstable(feature = "str_escape",
1906 reason = "return type may change to be an iterator",
1908 pub fn escape_debug(&self) -> String {
1909 self.chars().flat_map(|c| c.escape_debug()).collect()
1912 /// Escapes each char in `s` with [`char::escape_default`].
1914 /// [`char::escape_default`]: primitive.char.html#method.escape_default
1915 #[unstable(feature = "str_escape",
1916 reason = "return type may change to be an iterator",
1918 pub fn escape_default(&self) -> String {
1919 self.chars().flat_map(|c| c.escape_default()).collect()
1922 /// Escapes each char in `s` with [`char::escape_unicode`].
1924 /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
1925 #[unstable(feature = "str_escape",
1926 reason = "return type may change to be an iterator",
1928 pub fn escape_unicode(&self) -> String {
1929 self.chars().flat_map(|c| c.escape_unicode()).collect()
1932 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
1934 /// [`String`]: string/struct.String.html
1935 /// [`Box<str>`]: boxed/struct.Box.html
1942 /// let string = String::from("birthday gift");
1943 /// let boxed_str = string.clone().into_boxed_str();
1945 /// assert_eq!(boxed_str.into_string(), string);
1947 #[stable(feature = "box_str", since = "1.4.0")]
1948 pub fn into_string(self: Box<str>) -> String {
1950 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1951 String::from_utf8_unchecked(slice.into_vec())
1955 /// Create a [`String`] by repeating a string `n` times.
1957 /// [`String`]: string/struct.String.html
1964 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
1966 #[stable(feature = "repeat_str", since = "1.16.0")]
1967 pub fn repeat(&self, n: usize) -> String {
1968 let mut s = String::with_capacity(self.len() * n);
1969 s.extend((0..n).map(|_| self));