1 // Copyright 2012-2017 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 #[stable(feature = "rust1", since = "1.0.0")]
77 pub use std_unicode::str::SplitWhitespace;
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use core::str::pattern;
82 #[unstable(feature = "slice_concat_ext",
83 reason = "trait should not have to exist",
85 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
88 fn concat(&self) -> String {
93 // `len` calculation may overflow but push_str will check boundaries
94 let len = self.iter().map(|s| s.borrow().len()).sum();
95 let mut result = String::with_capacity(len);
98 result.push_str(s.borrow())
104 fn join(&self, sep: &str) -> String {
106 return String::new();
111 return self.concat();
114 // this is wrong without the guarantee that `self` is non-empty
115 // `len` calculation may overflow but push_str but will check boundaries
116 let len = sep.len() * (self.len() - 1) +
117 self.iter().map(|s| s.borrow().len()).sum::<usize>();
118 let mut result = String::with_capacity(len);
119 let mut first = true;
125 result.push_str(sep);
127 result.push_str(s.borrow());
132 fn connect(&self, sep: &str) -> String {
137 /// An iterator of [`u16`] over the string encoded as UTF-16.
139 /// [`u16`]: ../../std/primitive.u16.html
141 /// This struct is created by the [`encode_utf16`] method on [`str`].
142 /// See its documentation for more.
144 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
145 /// [`str`]: ../../std/primitive.str.html
147 #[stable(feature = "encode_utf16", since = "1.8.0")]
148 pub struct EncodeUtf16<'a> {
149 encoder: Utf16Encoder<Chars<'a>>,
152 #[stable(feature = "collection_debug", since = "1.17.0")]
153 impl<'a> fmt::Debug for EncodeUtf16<'a> {
154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
155 f.pad("EncodeUtf16 { .. }")
159 #[stable(feature = "encode_utf16", since = "1.8.0")]
160 impl<'a> Iterator for EncodeUtf16<'a> {
164 fn next(&mut self) -> Option<u16> {
169 fn size_hint(&self) -> (usize, Option<usize>) {
170 self.encoder.size_hint()
174 #[unstable(feature = "fused", issue = "35602")]
175 impl<'a> FusedIterator for EncodeUtf16<'a> {}
177 #[stable(feature = "rust1", since = "1.0.0")]
178 impl Borrow<str> for String {
180 fn borrow(&self) -> &str {
185 #[stable(feature = "rust1", since = "1.0.0")]
186 impl ToOwned for str {
188 fn to_owned(&self) -> String {
189 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
192 fn clone_into(&self, target: &mut String) {
193 let mut b = mem::replace(target, String::new()).into_bytes();
194 self.as_bytes().clone_into(&mut b);
195 *target = unsafe { String::from_utf8_unchecked(b) }
199 /// Methods for string slices.
203 /// Returns the length of `self`.
205 /// This length is in bytes, not [`char`]s or graphemes. In other words,
206 /// it may not be what a human considers the length of the string.
208 /// [`char`]: primitive.char.html
215 /// let len = "foo".len();
216 /// assert_eq!(3, len);
218 /// let len = "ƒoo".len(); // fancy f!
219 /// assert_eq!(4, len);
221 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn len(&self) -> usize {
224 core_str::StrExt::len(self)
227 /// Returns `true` if `self` has a length of zero bytes.
235 /// assert!(s.is_empty());
237 /// let s = "not empty";
238 /// assert!(!s.is_empty());
241 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn is_empty(&self) -> bool {
243 core_str::StrExt::is_empty(self)
246 /// Checks that `index`-th byte lies at the start and/or end of a
247 /// UTF-8 code point sequence.
249 /// The start and end of the string (when `index == self.len()`) are
253 /// Returns `false` if `index` is greater than `self.len()`.
258 /// let s = "Löwe 老虎 Léopard";
259 /// assert!(s.is_char_boundary(0));
261 /// assert!(s.is_char_boundary(6));
262 /// assert!(s.is_char_boundary(s.len()));
264 /// // second byte of `ö`
265 /// assert!(!s.is_char_boundary(2));
267 /// // third byte of `老`
268 /// assert!(!s.is_char_boundary(8));
270 #[stable(feature = "is_char_boundary", since = "1.9.0")]
272 pub fn is_char_boundary(&self, index: usize) -> bool {
273 core_str::StrExt::is_char_boundary(self, index)
276 /// Converts a string slice to a byte slice. To convert the byte slice back
277 /// into a string slice, use the [`str::from_utf8`] function.
279 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
286 /// let bytes = "bors".as_bytes();
287 /// assert_eq!(b"bors", bytes);
289 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn as_bytes(&self) -> &[u8] {
292 core_str::StrExt::as_bytes(self)
295 /// Converts a mutable string slice to a mutable byte slice. To convert the
296 /// mutable byte slice back into a mutable string slice, use the
297 /// [`str::from_utf8_mut`] function.
299 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
300 #[stable(feature = "str_mut_extras", since = "1.20.0")]
302 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
303 core_str::StrExt::as_bytes_mut(self)
306 /// Converts a string slice to a raw pointer.
308 /// As string slices are a slice of bytes, the raw pointer points to a
309 /// [`u8`]. This pointer will be pointing to the first byte of the string
312 /// [`u8`]: primitive.u8.html
320 /// let ptr = s.as_ptr();
322 #[stable(feature = "rust1", since = "1.0.0")]
324 pub fn as_ptr(&self) -> *const u8 {
325 core_str::StrExt::as_ptr(self)
328 /// Returns a subslice of `str`.
330 /// This is the non-panicking alternative to indexing the `str`. Returns
331 /// [`None`] whenever equivalent indexing operation would panic.
333 /// [`None`]: option/enum.Option.html#variant.None
338 /// let mut v = String::from("🗻∈🌏");
340 /// assert_eq!(Some("🗻"), v.get(0..4));
342 /// // indices not on UTF-8 sequence boundaries
343 /// assert!(v.get_mut(1..).is_none());
344 /// assert!(v.get_mut(..8).is_none());
347 /// assert!(v.get_mut(..42).is_none());
349 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
351 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
352 core_str::StrExt::get(self, i)
355 /// Returns a mutable subslice of `str`.
357 /// This is the non-panicking alternative to indexing the `str`. Returns
358 /// [`None`] whenever equivalent indexing operation would panic.
360 /// [`None`]: option/enum.Option.html#variant.None
365 /// use std::ascii::AsciiExt;
367 /// let mut v = String::from("hello");
368 /// // correct length
369 /// assert!(v.get_mut(0..5).is_some());
371 /// assert!(v.get_mut(..42).is_none());
372 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
374 /// assert_eq!("hello", v);
376 /// let s = v.get_mut(0..2);
377 /// let s = s.map(|s| {
378 /// s.make_ascii_uppercase();
381 /// assert_eq!(Some("HE"), s);
383 /// assert_eq!("HEllo", v);
385 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
387 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
388 core_str::StrExt::get_mut(self, i)
391 /// Returns a unchecked subslice of `str`.
393 /// This is the unchecked alternative to indexing the `str`.
397 /// Callers of this function are responsible that these preconditions are
400 /// * The starting index must come before the ending index;
401 /// * Indexes must be within bounds of the original slice;
402 /// * Indexes must lie on UTF-8 sequence boundaries.
404 /// Failing that, the returned string slice may reference invalid memory or
405 /// violate the invariants communicated by the `str` type.
412 /// assert_eq!("🗻", v.get_unchecked(0..4));
413 /// assert_eq!("∈", v.get_unchecked(4..7));
414 /// assert_eq!("🌏", v.get_unchecked(7..11));
417 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
419 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
420 core_str::StrExt::get_unchecked(self, i)
423 /// Returns a mutable, unchecked subslice of `str`.
425 /// This is the unchecked alternative to indexing the `str`.
429 /// Callers of this function are responsible that these preconditions are
432 /// * The starting index must come before the ending index;
433 /// * Indexes must be within bounds of the original slice;
434 /// * Indexes must lie on UTF-8 sequence boundaries.
436 /// Failing that, the returned string slice may reference invalid memory or
437 /// violate the invariants communicated by the `str` type.
442 /// let mut v = String::from("🗻∈🌏");
444 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
445 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
446 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
449 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
451 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
452 core_str::StrExt::get_unchecked_mut(self, i)
455 /// Creates a string slice from another string slice, bypassing safety
458 /// This is generally not recommended, use with caution! For a safe
459 /// alternative see [`str`] and [`Index`].
461 /// [`str`]: primitive.str.html
462 /// [`Index`]: ops/trait.Index.html
464 /// This new slice goes from `begin` to `end`, including `begin` but
467 /// To get a mutable string slice instead, see the
468 /// [`slice_mut_unchecked`] method.
470 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
474 /// Callers of this function are responsible that three preconditions are
477 /// * `begin` must come before `end`.
478 /// * `begin` and `end` must be byte positions within the string slice.
479 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
486 /// let s = "Löwe 老虎 Léopard";
489 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
492 /// let s = "Hello, world!";
495 /// assert_eq!("world", s.slice_unchecked(7, 12));
498 #[stable(feature = "rust1", since = "1.0.0")]
500 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
501 core_str::StrExt::slice_unchecked(self, begin, end)
504 /// Creates a string slice from another string slice, bypassing safety
506 /// This is generally not recommended, use with caution! For a safe
507 /// alternative see [`str`] and [`IndexMut`].
509 /// [`str`]: primitive.str.html
510 /// [`IndexMut`]: ops/trait.IndexMut.html
512 /// This new slice goes from `begin` to `end`, including `begin` but
515 /// To get an immutable string slice instead, see the
516 /// [`slice_unchecked`] method.
518 /// [`slice_unchecked`]: #method.slice_unchecked
522 /// Callers of this function are responsible that three preconditions are
525 /// * `begin` must come before `end`.
526 /// * `begin` and `end` must be byte positions within the string slice.
527 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
528 #[stable(feature = "str_slice_mut", since = "1.5.0")]
530 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
531 core_str::StrExt::slice_mut_unchecked(self, begin, end)
534 /// Divide one string slice into two at an index.
536 /// The argument, `mid`, should be a byte offset from the start of the
537 /// string. It must also be on the boundary of a UTF-8 code point.
539 /// The two slices returned go from the start of the string slice to `mid`,
540 /// and from `mid` to the end of the string slice.
542 /// To get mutable string slices instead, see the [`split_at_mut`]
545 /// [`split_at_mut`]: #method.split_at_mut
549 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
550 /// beyond the last code point of the string slice.
557 /// let s = "Per Martin-Löf";
559 /// let (first, last) = s.split_at(3);
561 /// assert_eq!("Per", first);
562 /// assert_eq!(" Martin-Löf", last);
565 #[stable(feature = "str_split_at", since = "1.4.0")]
566 pub fn split_at(&self, mid: usize) -> (&str, &str) {
567 core_str::StrExt::split_at(self, mid)
570 /// Divide one mutable string slice into two at an index.
572 /// The argument, `mid`, should be a byte offset from the start of the
573 /// string. It must also be on the boundary of a UTF-8 code point.
575 /// The two slices returned go from the start of the string slice to `mid`,
576 /// and from `mid` to the end of the string slice.
578 /// To get immutable string slices instead, see the [`split_at`] method.
580 /// [`split_at`]: #method.split_at
584 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
585 /// beyond the last code point of the string slice.
592 /// use std::ascii::AsciiExt;
594 /// let mut s = "Per Martin-Löf".to_string();
596 /// let (first, last) = s.split_at_mut(3);
597 /// first.make_ascii_uppercase();
598 /// assert_eq!("PER", first);
599 /// assert_eq!(" Martin-Löf", last);
601 /// assert_eq!("PER Martin-Löf", s);
604 #[stable(feature = "str_split_at", since = "1.4.0")]
605 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
606 core_str::StrExt::split_at_mut(self, mid)
609 /// Returns an iterator over the [`char`]s of a string slice.
611 /// As a string slice consists of valid UTF-8, we can iterate through a
612 /// string slice by [`char`]. This method returns such an iterator.
614 /// It's important to remember that [`char`] represents a Unicode Scalar
615 /// Value, and may not match your idea of what a 'character' is. Iteration
616 /// over grapheme clusters may be what you actually want.
618 /// [`char`]: primitive.char.html
625 /// let word = "goodbye";
627 /// let count = word.chars().count();
628 /// assert_eq!(7, count);
630 /// let mut chars = word.chars();
632 /// assert_eq!(Some('g'), chars.next());
633 /// assert_eq!(Some('o'), chars.next());
634 /// assert_eq!(Some('o'), chars.next());
635 /// assert_eq!(Some('d'), chars.next());
636 /// assert_eq!(Some('b'), chars.next());
637 /// assert_eq!(Some('y'), chars.next());
638 /// assert_eq!(Some('e'), chars.next());
640 /// assert_eq!(None, chars.next());
643 /// Remember, [`char`]s may not match your human intuition about characters:
648 /// let mut chars = y.chars();
650 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
651 /// assert_eq!(Some('\u{0306}'), chars.next());
653 /// assert_eq!(None, chars.next());
655 #[stable(feature = "rust1", since = "1.0.0")]
657 pub fn chars(&self) -> Chars {
658 core_str::StrExt::chars(self)
660 /// Returns an iterator over the [`char`]s of a string slice, and their
663 /// As a string slice consists of valid UTF-8, we can iterate through a
664 /// string slice by [`char`]. This method returns an iterator of both
665 /// these [`char`]s, as well as their byte positions.
667 /// The iterator yields tuples. The position is first, the [`char`] is
670 /// [`char`]: primitive.char.html
677 /// let word = "goodbye";
679 /// let count = word.char_indices().count();
680 /// assert_eq!(7, count);
682 /// let mut char_indices = word.char_indices();
684 /// assert_eq!(Some((0, 'g')), char_indices.next());
685 /// assert_eq!(Some((1, 'o')), char_indices.next());
686 /// assert_eq!(Some((2, 'o')), char_indices.next());
687 /// assert_eq!(Some((3, 'd')), char_indices.next());
688 /// assert_eq!(Some((4, 'b')), char_indices.next());
689 /// assert_eq!(Some((5, 'y')), char_indices.next());
690 /// assert_eq!(Some((6, 'e')), char_indices.next());
692 /// assert_eq!(None, char_indices.next());
695 /// Remember, [`char`]s may not match your human intuition about characters:
700 /// let mut char_indices = y.char_indices();
702 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
703 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
705 /// assert_eq!(None, char_indices.next());
707 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn char_indices(&self) -> CharIndices {
710 core_str::StrExt::char_indices(self)
713 /// An iterator over the bytes of a string slice.
715 /// As a string slice consists of a sequence of bytes, we can iterate
716 /// through a string slice by byte. This method returns such an iterator.
723 /// let mut bytes = "bors".bytes();
725 /// assert_eq!(Some(b'b'), bytes.next());
726 /// assert_eq!(Some(b'o'), bytes.next());
727 /// assert_eq!(Some(b'r'), bytes.next());
728 /// assert_eq!(Some(b's'), bytes.next());
730 /// assert_eq!(None, bytes.next());
732 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn bytes(&self) -> Bytes {
735 core_str::StrExt::bytes(self)
738 /// Split a string slice by whitespace.
740 /// The iterator returned will return string slices that are sub-slices of
741 /// the original string slice, separated by any amount of whitespace.
743 /// 'Whitespace' is defined according to the terms of the Unicode Derived
744 /// Core Property `White_Space`.
751 /// let mut iter = "A few words".split_whitespace();
753 /// assert_eq!(Some("A"), iter.next());
754 /// assert_eq!(Some("few"), iter.next());
755 /// assert_eq!(Some("words"), iter.next());
757 /// assert_eq!(None, iter.next());
760 /// All kinds of whitespace are considered:
763 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
764 /// assert_eq!(Some("Mary"), iter.next());
765 /// assert_eq!(Some("had"), iter.next());
766 /// assert_eq!(Some("a"), iter.next());
767 /// assert_eq!(Some("little"), iter.next());
768 /// assert_eq!(Some("lamb"), iter.next());
770 /// assert_eq!(None, iter.next());
772 #[stable(feature = "split_whitespace", since = "1.1.0")]
774 pub fn split_whitespace(&self) -> SplitWhitespace {
775 UnicodeStr::split_whitespace(self)
778 /// An iterator over the lines of a string, as string slices.
780 /// Lines are ended with either a newline (`\n`) or a carriage return with
781 /// a line feed (`\r\n`).
783 /// The final line ending is optional.
790 /// let text = "foo\r\nbar\n\nbaz\n";
791 /// let mut lines = text.lines();
793 /// assert_eq!(Some("foo"), lines.next());
794 /// assert_eq!(Some("bar"), lines.next());
795 /// assert_eq!(Some(""), lines.next());
796 /// assert_eq!(Some("baz"), lines.next());
798 /// assert_eq!(None, lines.next());
801 /// The final line ending isn't required:
804 /// let text = "foo\nbar\n\r\nbaz";
805 /// let mut lines = text.lines();
807 /// assert_eq!(Some("foo"), lines.next());
808 /// assert_eq!(Some("bar"), lines.next());
809 /// assert_eq!(Some(""), lines.next());
810 /// assert_eq!(Some("baz"), lines.next());
812 /// assert_eq!(None, lines.next());
814 #[stable(feature = "rust1", since = "1.0.0")]
816 pub fn lines(&self) -> Lines {
817 core_str::StrExt::lines(self)
820 /// An iterator over the lines of a string.
821 #[stable(feature = "rust1", since = "1.0.0")]
822 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
825 pub fn lines_any(&self) -> LinesAny {
826 core_str::StrExt::lines_any(self)
829 /// Returns an iterator of `u16` over the string encoded as UTF-16.
830 #[stable(feature = "encode_utf16", since = "1.8.0")]
831 pub fn encode_utf16(&self) -> EncodeUtf16 {
832 EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
835 /// Returns `true` if the given pattern matches a sub-slice of
836 /// this string slice.
838 /// Returns `false` if it does not.
845 /// let bananas = "bananas";
847 /// assert!(bananas.contains("nana"));
848 /// assert!(!bananas.contains("apples"));
850 #[stable(feature = "rust1", since = "1.0.0")]
852 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
853 core_str::StrExt::contains(self, pat)
856 /// Returns `true` if the given pattern matches a prefix of this
859 /// Returns `false` if it does not.
866 /// let bananas = "bananas";
868 /// assert!(bananas.starts_with("bana"));
869 /// assert!(!bananas.starts_with("nana"));
871 #[stable(feature = "rust1", since = "1.0.0")]
872 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
873 core_str::StrExt::starts_with(self, pat)
876 /// Returns `true` if the given pattern matches a suffix of this
879 /// Returns `false` if it does not.
886 /// let bananas = "bananas";
888 /// assert!(bananas.ends_with("anas"));
889 /// assert!(!bananas.ends_with("nana"));
891 #[stable(feature = "rust1", since = "1.0.0")]
892 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
893 where P::Searcher: ReverseSearcher<'a>
895 core_str::StrExt::ends_with(self, pat)
898 /// Returns the byte index of the first character of this string slice that
899 /// matches the pattern.
901 /// Returns [`None`] if the pattern doesn't match.
903 /// The pattern can be a `&str`, [`char`], or a closure that determines if
904 /// a character matches.
906 /// [`char`]: primitive.char.html
907 /// [`None`]: option/enum.Option.html#variant.None
914 /// let s = "Löwe 老虎 Léopard";
916 /// assert_eq!(s.find('L'), Some(0));
917 /// assert_eq!(s.find('é'), Some(14));
918 /// assert_eq!(s.find("Léopard"), Some(13));
921 /// More complex patterns with closures:
924 /// let s = "Löwe 老虎 Léopard";
926 /// assert_eq!(s.find(char::is_whitespace), Some(5));
927 /// assert_eq!(s.find(char::is_lowercase), Some(1));
930 /// Not finding the pattern:
933 /// let s = "Löwe 老虎 Léopard";
934 /// let x: &[_] = &['1', '2'];
936 /// assert_eq!(s.find(x), None);
938 #[stable(feature = "rust1", since = "1.0.0")]
940 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
941 core_str::StrExt::find(self, pat)
944 /// Returns the byte index of the last character of this string slice that
945 /// matches the pattern.
947 /// Returns [`None`] if the pattern doesn't match.
949 /// The pattern can be a `&str`, [`char`], or a closure that determines if
950 /// a character matches.
952 /// [`char`]: primitive.char.html
953 /// [`None`]: option/enum.Option.html#variant.None
960 /// let s = "Löwe 老虎 Léopard";
962 /// assert_eq!(s.rfind('L'), Some(13));
963 /// assert_eq!(s.rfind('é'), Some(14));
966 /// More complex patterns with closures:
969 /// let s = "Löwe 老虎 Léopard";
971 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
972 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
975 /// Not finding the pattern:
978 /// let s = "Löwe 老虎 Léopard";
979 /// let x: &[_] = &['1', '2'];
981 /// assert_eq!(s.rfind(x), None);
983 #[stable(feature = "rust1", since = "1.0.0")]
985 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
986 where P::Searcher: ReverseSearcher<'a>
988 core_str::StrExt::rfind(self, pat)
991 /// An iterator over substrings of this string slice, separated by
992 /// characters matched by a pattern.
994 /// The pattern can be a `&str`, [`char`], or a closure that determines the
997 /// # Iterator behavior
999 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1000 /// allows a reverse search and forward/reverse search yields the same
1001 /// elements. This is true for, eg, [`char`] but not for `&str`.
1003 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1005 /// If the pattern allows a reverse search but its results might differ
1006 /// from a forward search, the [`rsplit`] method can be used.
1008 /// [`char`]: primitive.char.html
1009 /// [`rsplit`]: #method.rsplit
1013 /// Simple patterns:
1016 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1017 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1019 /// let v: Vec<&str> = "".split('X').collect();
1020 /// assert_eq!(v, [""]);
1022 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1023 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1025 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1026 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1028 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1029 /// assert_eq!(v, ["abc", "def", "ghi"]);
1031 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1032 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1035 /// A more complex pattern, using a closure:
1038 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1039 /// assert_eq!(v, ["abc", "def", "ghi"]);
1042 /// If a string contains multiple contiguous separators, you will end up
1043 /// with empty strings in the output:
1046 /// let x = "||||a||b|c".to_string();
1047 /// let d: Vec<_> = x.split('|').collect();
1049 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1052 /// Contiguous separators are separated by the empty string.
1055 /// let x = "(///)".to_string();
1056 /// let d: Vec<_> = x.split('/').collect();
1058 /// assert_eq!(d, &["(", "", "", ")"]);
1061 /// Separators at the start or end of a string are neighbored
1062 /// by empty strings.
1065 /// let d: Vec<_> = "010".split("0").collect();
1066 /// assert_eq!(d, &["", "1", ""]);
1069 /// When the empty string is used as a separator, it separates
1070 /// every character in the string, along with the beginning
1071 /// and end of the string.
1074 /// let f: Vec<_> = "rust".split("").collect();
1075 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1078 /// Contiguous separators can lead to possibly surprising behavior
1079 /// when whitespace is used as the separator. This code is correct:
1082 /// let x = " a b c".to_string();
1083 /// let d: Vec<_> = x.split(' ').collect();
1085 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1088 /// It does _not_ give you:
1091 /// assert_eq!(d, &["a", "b", "c"]);
1094 /// Use [`split_whitespace`] for this behavior.
1096 /// [`split_whitespace`]: #method.split_whitespace
1097 #[stable(feature = "rust1", since = "1.0.0")]
1099 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1100 core_str::StrExt::split(self, pat)
1103 /// An iterator over substrings of the given string slice, separated by
1104 /// characters matched by a pattern and yielded in reverse order.
1106 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1109 /// [`char`]: primitive.char.html
1111 /// # Iterator behavior
1113 /// The returned iterator requires that the pattern supports a reverse
1114 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1115 /// search yields the same elements.
1117 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1119 /// For iterating from the front, the [`split`] method can be used.
1121 /// [`split`]: #method.split
1125 /// Simple patterns:
1128 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1129 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1131 /// let v: Vec<&str> = "".rsplit('X').collect();
1132 /// assert_eq!(v, [""]);
1134 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1135 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1137 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1138 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1141 /// A more complex pattern, using a closure:
1144 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1145 /// assert_eq!(v, ["ghi", "def", "abc"]);
1147 #[stable(feature = "rust1", since = "1.0.0")]
1149 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1150 where P::Searcher: ReverseSearcher<'a>
1152 core_str::StrExt::rsplit(self, pat)
1155 /// An iterator over substrings of the given string slice, separated by
1156 /// characters matched by a pattern.
1158 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1161 /// Equivalent to [`split`], except that the trailing substring
1162 /// is skipped if empty.
1164 /// [`split`]: #method.split
1166 /// This method can be used for string data that is _terminated_,
1167 /// rather than _separated_ by a pattern.
1169 /// # Iterator behavior
1171 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1172 /// allows a reverse search and forward/reverse search yields the same
1173 /// elements. This is true for, eg, [`char`] but not for `&str`.
1175 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1176 /// [`char`]: primitive.char.html
1178 /// If the pattern allows a reverse search but its results might differ
1179 /// from a forward search, the [`rsplit_terminator`] method can be used.
1181 /// [`rsplit_terminator`]: #method.rsplit_terminator
1188 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1189 /// assert_eq!(v, ["A", "B"]);
1191 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1192 /// assert_eq!(v, ["A", "", "B", ""]);
1194 #[stable(feature = "rust1", since = "1.0.0")]
1196 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1197 core_str::StrExt::split_terminator(self, pat)
1200 /// An iterator over substrings of `self`, separated by characters
1201 /// matched by a pattern and yielded in reverse order.
1203 /// The pattern can be a simple `&str`, [`char`], or a closure that
1204 /// determines the split.
1205 /// Additional libraries might provide more complex patterns like
1206 /// regular expressions.
1208 /// [`char`]: primitive.char.html
1210 /// Equivalent to [`split`], except that the trailing substring is
1211 /// skipped if empty.
1213 /// [`split`]: #method.split
1215 /// This method can be used for string data that is _terminated_,
1216 /// rather than _separated_ by a pattern.
1218 /// # Iterator behavior
1220 /// The returned iterator requires that the pattern supports a
1221 /// reverse search, and it will be double ended if a forward/reverse
1222 /// search yields the same elements.
1224 /// For iterating from the front, the [`split_terminator`] method can be
1227 /// [`split_terminator`]: #method.split_terminator
1232 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1233 /// assert_eq!(v, ["B", "A"]);
1235 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1236 /// assert_eq!(v, ["", "B", "", "A"]);
1238 #[stable(feature = "rust1", since = "1.0.0")]
1240 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1241 where P::Searcher: ReverseSearcher<'a>
1243 core_str::StrExt::rsplit_terminator(self, pat)
1246 /// An iterator over substrings of the given string slice, separated by a
1247 /// pattern, restricted to returning at most `n` items.
1249 /// If `n` substrings are returned, the last substring (the `n`th substring)
1250 /// will contain the remainder of the string.
1252 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1255 /// [`char`]: primitive.char.html
1257 /// # Iterator behavior
1259 /// The returned iterator will not be double ended, because it is
1260 /// not efficient to support.
1262 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1265 /// [`rsplitn`]: #method.rsplitn
1269 /// Simple patterns:
1272 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1273 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1275 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1276 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1278 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1279 /// assert_eq!(v, ["abcXdef"]);
1281 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1282 /// assert_eq!(v, [""]);
1285 /// A more complex pattern, using a closure:
1288 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1289 /// assert_eq!(v, ["abc", "defXghi"]);
1291 #[stable(feature = "rust1", since = "1.0.0")]
1293 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1294 core_str::StrExt::splitn(self, n, pat)
1297 /// An iterator over substrings of this string slice, separated by a
1298 /// pattern, starting from the end of the string, restricted to returning
1299 /// at most `n` items.
1301 /// If `n` substrings are returned, the last substring (the `n`th substring)
1302 /// will contain the remainder of the string.
1304 /// The pattern can be a `&str`, [`char`], or a closure that
1305 /// determines the split.
1307 /// [`char`]: primitive.char.html
1309 /// # Iterator behavior
1311 /// The returned iterator will not be double ended, because it is not
1312 /// efficient to support.
1314 /// For splitting from the front, the [`splitn`] method can be used.
1316 /// [`splitn`]: #method.splitn
1320 /// Simple patterns:
1323 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1324 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1326 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1327 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1329 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1330 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1333 /// A more complex pattern, using a closure:
1336 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1337 /// assert_eq!(v, ["ghi", "abc1def"]);
1339 #[stable(feature = "rust1", since = "1.0.0")]
1341 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1342 where P::Searcher: ReverseSearcher<'a>
1344 core_str::StrExt::rsplitn(self, n, pat)
1347 /// An iterator over the disjoint matches of a pattern within the given string
1350 /// The pattern can be a `&str`, [`char`], or a closure that
1351 /// determines if a character matches.
1353 /// [`char`]: primitive.char.html
1355 /// # Iterator behavior
1357 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1358 /// allows a reverse search and forward/reverse search yields the same
1359 /// elements. This is true for, eg, [`char`] but not for `&str`.
1361 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1362 /// [`char`]: primitive.char.html
1364 /// If the pattern allows a reverse search but its results might differ
1365 /// from a forward search, the [`rmatches`] method can be used.
1367 /// [`rmatches`]: #method.rmatches
1374 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1375 /// assert_eq!(v, ["abc", "abc", "abc"]);
1377 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1378 /// assert_eq!(v, ["1", "2", "3"]);
1380 #[stable(feature = "str_matches", since = "1.2.0")]
1382 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1383 core_str::StrExt::matches(self, pat)
1386 /// An iterator over the disjoint matches of a pattern within this string slice,
1387 /// yielded in reverse order.
1389 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1390 /// a character matches.
1392 /// [`char`]: primitive.char.html
1394 /// # Iterator behavior
1396 /// The returned iterator requires that the pattern supports a reverse
1397 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1398 /// search yields the same elements.
1400 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1402 /// For iterating from the front, the [`matches`] method can be used.
1404 /// [`matches`]: #method.matches
1411 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1412 /// assert_eq!(v, ["abc", "abc", "abc"]);
1414 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1415 /// assert_eq!(v, ["3", "2", "1"]);
1417 #[stable(feature = "str_matches", since = "1.2.0")]
1419 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1420 where P::Searcher: ReverseSearcher<'a>
1422 core_str::StrExt::rmatches(self, pat)
1425 /// An iterator over the disjoint matches of a pattern within this string
1426 /// slice as well as the index that the match starts at.
1428 /// For matches of `pat` within `self` that overlap, only the indices
1429 /// corresponding to the first match are returned.
1431 /// The pattern can be a `&str`, [`char`], or a closure that determines
1432 /// if a character matches.
1434 /// [`char`]: primitive.char.html
1436 /// # Iterator behavior
1438 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1439 /// allows a reverse search and forward/reverse search yields the same
1440 /// elements. This is true for, eg, [`char`] but not for `&str`.
1442 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1444 /// If the pattern allows a reverse search but its results might differ
1445 /// from a forward search, the [`rmatch_indices`] method can be used.
1447 /// [`rmatch_indices`]: #method.rmatch_indices
1454 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1455 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1457 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1458 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1460 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1461 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1463 #[stable(feature = "str_match_indices", since = "1.5.0")]
1465 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1466 core_str::StrExt::match_indices(self, pat)
1469 /// An iterator over the disjoint matches of a pattern within `self`,
1470 /// yielded in reverse order along with the index of the match.
1472 /// For matches of `pat` within `self` that overlap, only the indices
1473 /// corresponding to the last match are returned.
1475 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1476 /// character matches.
1478 /// [`char`]: primitive.char.html
1480 /// # Iterator behavior
1482 /// The returned iterator requires that the pattern supports a reverse
1483 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1484 /// search yields the same elements.
1486 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1488 /// For iterating from the front, the [`match_indices`] method can be used.
1490 /// [`match_indices`]: #method.match_indices
1497 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1498 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1500 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1501 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1503 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1504 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1506 #[stable(feature = "str_match_indices", since = "1.5.0")]
1508 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1509 where P::Searcher: ReverseSearcher<'a>
1511 core_str::StrExt::rmatch_indices(self, pat)
1514 /// Returns a string slice with leading and trailing whitespace removed.
1516 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1517 /// Core Property `White_Space`.
1524 /// let s = " Hello\tworld\t";
1526 /// assert_eq!("Hello\tworld", s.trim());
1528 #[stable(feature = "rust1", since = "1.0.0")]
1529 pub fn trim(&self) -> &str {
1530 UnicodeStr::trim(self)
1533 /// Returns a string slice with leading whitespace removed.
1535 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1536 /// Core Property `White_Space`.
1538 /// # Text directionality
1540 /// A string is a sequence of bytes. 'Left' in this context means the first
1541 /// position of that byte string; for a language like Arabic or Hebrew
1542 /// which are 'right to left' rather than 'left to right', this will be
1543 /// the _right_ side, not the left.
1550 /// let s = " Hello\tworld\t";
1552 /// assert_eq!("Hello\tworld\t", s.trim_left());
1558 /// let s = " English";
1559 /// assert!(Some('E') == s.trim_left().chars().next());
1561 /// let s = " עברית";
1562 /// assert!(Some('ע') == s.trim_left().chars().next());
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 pub fn trim_left(&self) -> &str {
1566 UnicodeStr::trim_left(self)
1569 /// Returns a string slice with trailing whitespace removed.
1571 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1572 /// Core Property `White_Space`.
1574 /// # Text directionality
1576 /// A string is a sequence of bytes. 'Right' in this context means the last
1577 /// position of that byte string; for a language like Arabic or Hebrew
1578 /// which are 'right to left' rather than 'left to right', this will be
1579 /// the _left_ side, not the right.
1586 /// let s = " Hello\tworld\t";
1588 /// assert_eq!(" Hello\tworld", s.trim_right());
1594 /// let s = "English ";
1595 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1597 /// let s = "עברית ";
1598 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 pub fn trim_right(&self) -> &str {
1602 UnicodeStr::trim_right(self)
1605 /// Returns a string slice with all prefixes and suffixes that match a
1606 /// pattern repeatedly removed.
1608 /// The pattern can be a [`char`] or a closure that determines if a
1609 /// character matches.
1611 /// [`char`]: primitive.char.html
1615 /// Simple patterns:
1618 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1619 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1621 /// let x: &[_] = &['1', '2'];
1622 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1625 /// A more complex pattern, using a closure:
1628 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1632 where P::Searcher: DoubleEndedSearcher<'a>
1634 core_str::StrExt::trim_matches(self, pat)
1637 /// Returns a string slice with all prefixes that match a pattern
1638 /// repeatedly removed.
1640 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1641 /// a character matches.
1643 /// [`char`]: primitive.char.html
1645 /// # Text directionality
1647 /// A string is a sequence of bytes. 'Left' in this context means the first
1648 /// position of that byte string; for a language like Arabic or Hebrew
1649 /// which are 'right to left' rather than 'left to right', this will be
1650 /// the _right_ side, not the left.
1657 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1658 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1660 /// let x: &[_] = &['1', '2'];
1661 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1663 #[stable(feature = "rust1", since = "1.0.0")]
1664 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1665 core_str::StrExt::trim_left_matches(self, pat)
1668 /// Returns a string slice with all suffixes that match a pattern
1669 /// repeatedly removed.
1671 /// The pattern can be a `&str`, [`char`], or a closure that
1672 /// determines if a character matches.
1674 /// [`char`]: primitive.char.html
1676 /// # Text directionality
1678 /// A string is a sequence of bytes. 'Right' in this context means the last
1679 /// position of that byte string; for a language like Arabic or Hebrew
1680 /// which are 'right to left' rather than 'left to right', this will be
1681 /// the _left_ side, not the right.
1685 /// Simple patterns:
1688 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1689 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1691 /// let x: &[_] = &['1', '2'];
1692 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1695 /// A more complex pattern, using a closure:
1698 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1702 where P::Searcher: ReverseSearcher<'a>
1704 core_str::StrExt::trim_right_matches(self, pat)
1707 /// Parses this string slice into another type.
1709 /// Because `parse` is so general, it can cause problems with type
1710 /// inference. As such, `parse` is one of the few times you'll see
1711 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1712 /// helps the inference algorithm understand specifically which type
1713 /// you're trying to parse into.
1715 /// `parse` can parse any type that implements the [`FromStr`] trait.
1717 /// [`FromStr`]: str/trait.FromStr.html
1721 /// Will return [`Err`] if it's not possible to parse this string slice into
1722 /// the desired type.
1724 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1731 /// let four: u32 = "4".parse().unwrap();
1733 /// assert_eq!(4, four);
1736 /// Using the 'turbofish' instead of annotating `four`:
1739 /// let four = "4".parse::<u32>();
1741 /// assert_eq!(Ok(4), four);
1744 /// Failing to parse:
1747 /// let nope = "j".parse::<u32>();
1749 /// assert!(nope.is_err());
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1754 core_str::StrExt::parse(self)
1757 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
1758 #[stable(feature = "str_box_extras", since = "1.20.0")]
1759 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
1763 /// Replaces all matches of a pattern with another string.
1765 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1766 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1767 /// replaces them with the replacement string slice.
1769 /// [`String`]: string/struct.String.html
1776 /// let s = "this is old";
1778 /// assert_eq!("this is new", s.replace("old", "new"));
1781 /// When the pattern doesn't match:
1784 /// let s = "this is old";
1785 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1787 #[stable(feature = "rust1", since = "1.0.0")]
1789 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1790 let mut result = String::new();
1791 let mut last_end = 0;
1792 for (start, part) in self.match_indices(from) {
1793 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1794 result.push_str(to);
1795 last_end = start + part.len();
1797 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1801 /// Replaces first N matches of a pattern with another string.
1803 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1804 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1805 /// replaces them with the replacement string slice at most `count` times.
1807 /// [`String`]: string/struct.String.html
1814 /// let s = "foo foo 123 foo";
1815 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1816 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1817 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1820 /// When the pattern doesn't match:
1823 /// let s = "this is old";
1824 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1826 #[stable(feature = "str_replacen", since = "1.16.0")]
1827 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1828 // Hope to reduce the times of re-allocation
1829 let mut result = String::with_capacity(32);
1830 let mut last_end = 0;
1831 for (start, part) in self.match_indices(pat).take(count) {
1832 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1833 result.push_str(to);
1834 last_end = start + part.len();
1836 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1840 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1842 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1845 /// Since some characters can expand into multiple characters when changing
1846 /// the case, this function returns a [`String`] instead of modifying the
1847 /// parameter in-place.
1849 /// [`String`]: string/struct.String.html
1856 /// let s = "HELLO";
1858 /// assert_eq!("hello", s.to_lowercase());
1861 /// A tricky example, with sigma:
1864 /// let sigma = "Σ";
1866 /// assert_eq!("σ", sigma.to_lowercase());
1868 /// // but at the end of a word, it's ς, not σ:
1869 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1871 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1874 /// Languages without case are not changed:
1877 /// let new_year = "农历新年";
1879 /// assert_eq!(new_year, new_year.to_lowercase());
1881 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1882 pub fn to_lowercase(&self) -> String {
1883 let mut s = String::with_capacity(self.len());
1884 for (i, c) in self[..].char_indices() {
1886 // Σ maps to σ, except at the end of a word where it maps to ς.
1887 // This is the only conditional (contextual) but language-independent mapping
1888 // in `SpecialCasing.txt`,
1889 // so hard-code it rather than have a generic "condition" mechanism.
1890 // See https://github.com/rust-lang/rust/issues/26035
1891 map_uppercase_sigma(self, i, &mut s)
1893 s.extend(c.to_lowercase());
1898 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1899 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1900 // for the definition of `Final_Sigma`.
1901 debug_assert!('Σ'.len_utf8() == 2);
1902 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1903 !case_ignoreable_then_cased(from[i + 2..].chars());
1904 to.push_str(if is_word_final { "ς" } else { "σ" });
1907 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1908 use std_unicode::derived_property::{Cased, Case_Ignorable};
1909 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1910 Some(c) => Cased(c),
1916 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1918 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1921 /// Since some characters can expand into multiple characters when changing
1922 /// the case, this function returns a [`String`] instead of modifying the
1923 /// parameter in-place.
1925 /// [`String`]: string/struct.String.html
1932 /// let s = "hello";
1934 /// assert_eq!("HELLO", s.to_uppercase());
1937 /// Scripts without case are not changed:
1940 /// let new_year = "农历新年";
1942 /// assert_eq!(new_year, new_year.to_uppercase());
1944 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1945 pub fn to_uppercase(&self) -> String {
1946 let mut s = String::with_capacity(self.len());
1947 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1951 /// Escapes each char in `s` with [`char::escape_debug`].
1953 /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
1954 #[unstable(feature = "str_escape",
1955 reason = "return type may change to be an iterator",
1957 pub fn escape_debug(&self) -> String {
1958 self.chars().flat_map(|c| c.escape_debug()).collect()
1961 /// Escapes each char in `s` with [`char::escape_default`].
1963 /// [`char::escape_default`]: primitive.char.html#method.escape_default
1964 #[unstable(feature = "str_escape",
1965 reason = "return type may change to be an iterator",
1967 pub fn escape_default(&self) -> String {
1968 self.chars().flat_map(|c| c.escape_default()).collect()
1971 /// Escapes each char in `s` with [`char::escape_unicode`].
1973 /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
1974 #[unstable(feature = "str_escape",
1975 reason = "return type may change to be an iterator",
1977 pub fn escape_unicode(&self) -> String {
1978 self.chars().flat_map(|c| c.escape_unicode()).collect()
1981 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
1983 /// [`String`]: string/struct.String.html
1984 /// [`Box<str>`]: boxed/struct.Box.html
1991 /// let string = String::from("birthday gift");
1992 /// let boxed_str = string.clone().into_boxed_str();
1994 /// assert_eq!(boxed_str.into_string(), string);
1996 #[stable(feature = "box_str", since = "1.4.0")]
1997 pub fn into_string(self: Box<str>) -> String {
1999 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
2000 String::from_utf8_unchecked(slice.into_vec())
2004 /// Create a [`String`] by repeating a string `n` times.
2006 /// [`String`]: string/struct.String.html
2013 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
2015 #[stable(feature = "repeat_str", since = "1.16.0")]
2016 pub fn repeat(&self, n: usize) -> String {
2017 let mut s = String::with_capacity(self.len() * n);
2018 s.extend((0..n).map(|_| self));
2023 /// Converts a boxed slice of bytes to a boxed string slice without checking
2024 /// that the string contains valid UTF-8.
2025 #[stable(feature = "str_box_extras", since = "1.20.0")]
2026 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {