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 is generally not recommended, use with caution! For a safe
439 /// alternative see [`str`] and [`Index`].
441 /// [`str`]: primitive.str.html
442 /// [`Index`]: ops/trait.Index.html
444 /// This new slice goes from `begin` to `end`, including `begin` but
447 /// To get a mutable string slice instead, see the
448 /// [`slice_mut_unchecked`] method.
450 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
454 /// Callers of this function are responsible that three preconditions are
457 /// * `begin` must come before `end`.
458 /// * `begin` and `end` must be byte positions within the string slice.
459 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
466 /// let s = "Löwe 老虎 Léopard";
469 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
472 /// let s = "Hello, world!";
475 /// assert_eq!("world", s.slice_unchecked(7, 12));
478 #[stable(feature = "rust1", since = "1.0.0")]
480 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
481 core_str::StrExt::slice_unchecked(self, begin, end)
484 /// Creates a string slice from another string slice, bypassing safety
486 /// This is generally not recommended, use with caution! For a safe
487 /// alternative see [`str`] and [`IndexMut`].
489 /// [`str`]: primitive.str.html
490 /// [`IndexMut`]: ops/trait.IndexMut.html
492 /// This new slice goes from `begin` to `end`, including `begin` but
495 /// To get an immutable string slice instead, see the
496 /// [`slice_unchecked`] method.
498 /// [`slice_unchecked`]: #method.slice_unchecked
502 /// Callers of this function are responsible that three preconditions are
505 /// * `begin` must come before `end`.
506 /// * `begin` and `end` must be byte positions within the string slice.
507 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
508 #[stable(feature = "str_slice_mut", since = "1.5.0")]
510 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
511 core_str::StrExt::slice_mut_unchecked(self, begin, end)
514 /// Divide one string slice into two at an index.
516 /// The argument, `mid`, should be a byte offset from the start of the
517 /// string. It must also be on the boundary of a UTF-8 code point.
519 /// The two slices returned go from the start of the string slice to `mid`,
520 /// and from `mid` to the end of the string slice.
522 /// To get mutable string slices instead, see the [`split_at_mut`]
525 /// [`split_at_mut`]: #method.split_at_mut
529 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
530 /// beyond the last code point of the string slice.
537 /// let s = "Per Martin-Löf";
539 /// let (first, last) = s.split_at(3);
541 /// assert_eq!("Per", first);
542 /// assert_eq!(" Martin-Löf", last);
545 #[stable(feature = "str_split_at", since = "1.4.0")]
546 pub fn split_at(&self, mid: usize) -> (&str, &str) {
547 core_str::StrExt::split_at(self, mid)
550 /// Divide one mutable string slice into two at an index.
552 /// The argument, `mid`, should be a byte offset from the start of the
553 /// string. It must also be on the boundary of a UTF-8 code point.
555 /// The two slices returned go from the start of the string slice to `mid`,
556 /// and from `mid` to the end of the string slice.
558 /// To get immutable string slices instead, see the [`split_at`] method.
560 /// [`split_at`]: #method.split_at
564 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
565 /// beyond the last code point of the string slice.
572 /// let mut s = "Per Martin-Löf".to_string();
574 /// let (first, last) = s.split_at_mut(3);
576 /// assert_eq!("Per", first);
577 /// assert_eq!(" Martin-Löf", last);
580 #[stable(feature = "str_split_at", since = "1.4.0")]
581 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
582 core_str::StrExt::split_at_mut(self, mid)
585 /// Returns an iterator over the [`char`]s of a string slice.
587 /// As a string slice consists of valid UTF-8, we can iterate through a
588 /// string slice by [`char`]. This method returns such an iterator.
590 /// It's important to remember that [`char`] represents a Unicode Scalar
591 /// Value, and may not match your idea of what a 'character' is. Iteration
592 /// over grapheme clusters may be what you actually want.
594 /// [`char`]: primitive.char.html
601 /// let word = "goodbye";
603 /// let count = word.chars().count();
604 /// assert_eq!(7, count);
606 /// let mut chars = word.chars();
608 /// assert_eq!(Some('g'), chars.next());
609 /// assert_eq!(Some('o'), chars.next());
610 /// assert_eq!(Some('o'), chars.next());
611 /// assert_eq!(Some('d'), chars.next());
612 /// assert_eq!(Some('b'), chars.next());
613 /// assert_eq!(Some('y'), chars.next());
614 /// assert_eq!(Some('e'), chars.next());
616 /// assert_eq!(None, chars.next());
619 /// Remember, [`char`]s may not match your human intuition about characters:
624 /// let mut chars = y.chars();
626 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
627 /// assert_eq!(Some('\u{0306}'), chars.next());
629 /// assert_eq!(None, chars.next());
631 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn chars(&self) -> Chars {
634 core_str::StrExt::chars(self)
636 /// Returns an iterator over the [`char`]s of a string slice, and their
639 /// As a string slice consists of valid UTF-8, we can iterate through a
640 /// string slice by [`char`]. This method returns an iterator of both
641 /// these [`char`]s, as well as their byte positions.
643 /// The iterator yields tuples. The position is first, the [`char`] is
646 /// [`char`]: primitive.char.html
653 /// let word = "goodbye";
655 /// let count = word.char_indices().count();
656 /// assert_eq!(7, count);
658 /// let mut char_indices = word.char_indices();
660 /// assert_eq!(Some((0, 'g')), char_indices.next());
661 /// assert_eq!(Some((1, 'o')), char_indices.next());
662 /// assert_eq!(Some((2, 'o')), char_indices.next());
663 /// assert_eq!(Some((3, 'd')), char_indices.next());
664 /// assert_eq!(Some((4, 'b')), char_indices.next());
665 /// assert_eq!(Some((5, 'y')), char_indices.next());
666 /// assert_eq!(Some((6, 'e')), char_indices.next());
668 /// assert_eq!(None, char_indices.next());
671 /// Remember, [`char`]s may not match your human intuition about characters:
676 /// let mut char_indices = y.char_indices();
678 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
679 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
681 /// assert_eq!(None, char_indices.next());
683 #[stable(feature = "rust1", since = "1.0.0")]
685 pub fn char_indices(&self) -> CharIndices {
686 core_str::StrExt::char_indices(self)
689 /// An iterator over the bytes of a string slice.
691 /// As a string slice consists of a sequence of bytes, we can iterate
692 /// through a string slice by byte. This method returns such an iterator.
699 /// let mut bytes = "bors".bytes();
701 /// assert_eq!(Some(b'b'), bytes.next());
702 /// assert_eq!(Some(b'o'), bytes.next());
703 /// assert_eq!(Some(b'r'), bytes.next());
704 /// assert_eq!(Some(b's'), bytes.next());
706 /// assert_eq!(None, bytes.next());
708 #[stable(feature = "rust1", since = "1.0.0")]
710 pub fn bytes(&self) -> Bytes {
711 core_str::StrExt::bytes(self)
714 /// Split a string slice by whitespace.
716 /// The iterator returned will return string slices that are sub-slices of
717 /// the original string slice, separated by any amount of whitespace.
719 /// 'Whitespace' is defined according to the terms of the Unicode Derived
720 /// Core Property `White_Space`.
727 /// let mut iter = "A few words".split_whitespace();
729 /// assert_eq!(Some("A"), iter.next());
730 /// assert_eq!(Some("few"), iter.next());
731 /// assert_eq!(Some("words"), iter.next());
733 /// assert_eq!(None, iter.next());
736 /// All kinds of whitespace are considered:
739 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
740 /// assert_eq!(Some("Mary"), iter.next());
741 /// assert_eq!(Some("had"), iter.next());
742 /// assert_eq!(Some("a"), iter.next());
743 /// assert_eq!(Some("little"), iter.next());
744 /// assert_eq!(Some("lamb"), iter.next());
746 /// assert_eq!(None, iter.next());
748 #[stable(feature = "split_whitespace", since = "1.1.0")]
750 pub fn split_whitespace(&self) -> SplitWhitespace {
751 UnicodeStr::split_whitespace(self)
754 /// An iterator over the lines of a string, as string slices.
756 /// Lines are ended with either a newline (`\n`) or a carriage return with
757 /// a line feed (`\r\n`).
759 /// The final line ending is optional.
766 /// let text = "foo\r\nbar\n\nbaz\n";
767 /// let mut lines = text.lines();
769 /// assert_eq!(Some("foo"), lines.next());
770 /// assert_eq!(Some("bar"), lines.next());
771 /// assert_eq!(Some(""), lines.next());
772 /// assert_eq!(Some("baz"), lines.next());
774 /// assert_eq!(None, lines.next());
777 /// The final line ending isn't required:
780 /// let text = "foo\nbar\n\r\nbaz";
781 /// let mut lines = text.lines();
783 /// assert_eq!(Some("foo"), lines.next());
784 /// assert_eq!(Some("bar"), lines.next());
785 /// assert_eq!(Some(""), lines.next());
786 /// assert_eq!(Some("baz"), lines.next());
788 /// assert_eq!(None, lines.next());
790 #[stable(feature = "rust1", since = "1.0.0")]
792 pub fn lines(&self) -> Lines {
793 core_str::StrExt::lines(self)
796 /// An iterator over the lines of a string.
797 #[stable(feature = "rust1", since = "1.0.0")]
798 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
801 pub fn lines_any(&self) -> LinesAny {
802 core_str::StrExt::lines_any(self)
805 /// Returns an iterator of `u16` over the string encoded as UTF-16.
806 #[stable(feature = "encode_utf16", since = "1.8.0")]
807 pub fn encode_utf16(&self) -> EncodeUtf16 {
808 EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
811 /// Returns `true` if the given pattern matches a sub-slice of
812 /// this string slice.
814 /// Returns `false` if it does not.
821 /// let bananas = "bananas";
823 /// assert!(bananas.contains("nana"));
824 /// assert!(!bananas.contains("apples"));
826 #[stable(feature = "rust1", since = "1.0.0")]
828 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
829 core_str::StrExt::contains(self, pat)
832 /// Returns `true` if the given pattern matches a prefix of this
835 /// Returns `false` if it does not.
842 /// let bananas = "bananas";
844 /// assert!(bananas.starts_with("bana"));
845 /// assert!(!bananas.starts_with("nana"));
847 #[stable(feature = "rust1", since = "1.0.0")]
848 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
849 core_str::StrExt::starts_with(self, pat)
852 /// Returns `true` if the given pattern matches a suffix of this
855 /// Returns `false` if it does not.
862 /// let bananas = "bananas";
864 /// assert!(bananas.ends_with("anas"));
865 /// assert!(!bananas.ends_with("nana"));
867 #[stable(feature = "rust1", since = "1.0.0")]
868 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
869 where P::Searcher: ReverseSearcher<'a>
871 core_str::StrExt::ends_with(self, pat)
874 /// Returns the byte index of the first character of this string slice that
875 /// matches the pattern.
877 /// Returns [`None`] if the pattern doesn't match.
879 /// The pattern can be a `&str`, [`char`], or a closure that determines if
880 /// a character matches.
882 /// [`char`]: primitive.char.html
883 /// [`None`]: option/enum.Option.html#variant.None
890 /// let s = "Löwe 老虎 Léopard";
892 /// assert_eq!(s.find('L'), Some(0));
893 /// assert_eq!(s.find('é'), Some(14));
894 /// assert_eq!(s.find("Léopard"), Some(13));
897 /// More complex patterns with closures:
900 /// let s = "Löwe 老虎 Léopard";
902 /// assert_eq!(s.find(char::is_whitespace), Some(5));
903 /// assert_eq!(s.find(char::is_lowercase), Some(1));
906 /// Not finding the pattern:
909 /// let s = "Löwe 老虎 Léopard";
910 /// let x: &[_] = &['1', '2'];
912 /// assert_eq!(s.find(x), None);
914 #[stable(feature = "rust1", since = "1.0.0")]
916 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
917 core_str::StrExt::find(self, pat)
920 /// Returns the byte index of the last character of this string slice that
921 /// matches the pattern.
923 /// Returns [`None`] if the pattern doesn't match.
925 /// The pattern can be a `&str`, [`char`], or a closure that determines if
926 /// a character matches.
928 /// [`char`]: primitive.char.html
929 /// [`None`]: option/enum.Option.html#variant.None
936 /// let s = "Löwe 老虎 Léopard";
938 /// assert_eq!(s.rfind('L'), Some(13));
939 /// assert_eq!(s.rfind('é'), Some(14));
942 /// More complex patterns with closures:
945 /// let s = "Löwe 老虎 Léopard";
947 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
948 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
951 /// Not finding the pattern:
954 /// let s = "Löwe 老虎 Léopard";
955 /// let x: &[_] = &['1', '2'];
957 /// assert_eq!(s.rfind(x), None);
959 #[stable(feature = "rust1", since = "1.0.0")]
961 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
962 where P::Searcher: ReverseSearcher<'a>
964 core_str::StrExt::rfind(self, pat)
967 /// An iterator over substrings of this string slice, separated by
968 /// characters matched by a pattern.
970 /// The pattern can be a `&str`, [`char`], or a closure that determines the
973 /// # Iterator behavior
975 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
976 /// allows a reverse search and forward/reverse search yields the same
977 /// elements. This is true for, eg, [`char`] but not for `&str`.
979 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
981 /// If the pattern allows a reverse search but its results might differ
982 /// from a forward search, the [`rsplit`] method can be used.
984 /// [`char`]: primitive.char.html
985 /// [`rsplit`]: #method.rsplit
992 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
993 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
995 /// let v: Vec<&str> = "".split('X').collect();
996 /// assert_eq!(v, [""]);
998 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
999 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1001 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1002 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1004 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1005 /// assert_eq!(v, ["abc", "def", "ghi"]);
1007 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1008 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1011 /// A more complex pattern, using a closure:
1014 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1015 /// assert_eq!(v, ["abc", "def", "ghi"]);
1018 /// If a string contains multiple contiguous separators, you will end up
1019 /// with empty strings in the output:
1022 /// let x = "||||a||b|c".to_string();
1023 /// let d: Vec<_> = x.split('|').collect();
1025 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1028 /// Contiguous separators are separated by the empty string.
1031 /// let x = "(///)".to_string();
1032 /// let d: Vec<_> = x.split('/').collect();
1034 /// assert_eq!(d, &["(", "", "", ")"]);
1037 /// Separators at the start or end of a string are neighbored
1038 /// by empty strings.
1041 /// let d: Vec<_> = "010".split("0").collect();
1042 /// assert_eq!(d, &["", "1", ""]);
1045 /// When the empty string is used as a separator, it separates
1046 /// every character in the string, along with the beginning
1047 /// and end of the string.
1050 /// let f: Vec<_> = "rust".split("").collect();
1051 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1054 /// Contiguous separators can lead to possibly surprising behavior
1055 /// when whitespace is used as the separator. This code is correct:
1058 /// let x = " a b c".to_string();
1059 /// let d: Vec<_> = x.split(' ').collect();
1061 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1064 /// It does _not_ give you:
1067 /// assert_eq!(d, &["a", "b", "c"]);
1070 /// Use [`split_whitespace`] for this behavior.
1072 /// [`split_whitespace`]: #method.split_whitespace
1073 #[stable(feature = "rust1", since = "1.0.0")]
1075 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1076 core_str::StrExt::split(self, pat)
1079 /// An iterator over substrings of the given string slice, separated by
1080 /// characters matched by a pattern and yielded in reverse order.
1082 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1085 /// [`char`]: primitive.char.html
1087 /// # Iterator behavior
1089 /// The returned iterator requires that the pattern supports a reverse
1090 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1091 /// search yields the same elements.
1093 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1095 /// For iterating from the front, the [`split`] method can be used.
1097 /// [`split`]: #method.split
1101 /// Simple patterns:
1104 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1105 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1107 /// let v: Vec<&str> = "".rsplit('X').collect();
1108 /// assert_eq!(v, [""]);
1110 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1111 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1113 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1114 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1117 /// A more complex pattern, using a closure:
1120 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1121 /// assert_eq!(v, ["ghi", "def", "abc"]);
1123 #[stable(feature = "rust1", since = "1.0.0")]
1125 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1126 where P::Searcher: ReverseSearcher<'a>
1128 core_str::StrExt::rsplit(self, pat)
1131 /// An iterator over substrings of the given string slice, separated by
1132 /// characters matched by a pattern.
1134 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1137 /// Equivalent to [`split`], except that the trailing substring
1138 /// is skipped if empty.
1140 /// [`split`]: #method.split
1142 /// This method can be used for string data that is _terminated_,
1143 /// rather than _separated_ by a pattern.
1145 /// # Iterator behavior
1147 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1148 /// allows a reverse search and forward/reverse search yields the same
1149 /// elements. This is true for, eg, [`char`] but not for `&str`.
1151 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1152 /// [`char`]: primitive.char.html
1154 /// If the pattern allows a reverse search but its results might differ
1155 /// from a forward search, the [`rsplit_terminator`] method can be used.
1157 /// [`rsplit_terminator`]: #method.rsplit_terminator
1164 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1165 /// assert_eq!(v, ["A", "B"]);
1167 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1168 /// assert_eq!(v, ["A", "", "B", ""]);
1170 #[stable(feature = "rust1", since = "1.0.0")]
1172 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1173 core_str::StrExt::split_terminator(self, pat)
1176 /// An iterator over substrings of `self`, separated by characters
1177 /// matched by a pattern and yielded in reverse order.
1179 /// The pattern can be a simple `&str`, [`char`], or a closure that
1180 /// determines the split.
1181 /// Additional libraries might provide more complex patterns like
1182 /// regular expressions.
1184 /// [`char`]: primitive.char.html
1186 /// Equivalent to [`split`], except that the trailing substring is
1187 /// skipped if empty.
1189 /// [`split`]: #method.split
1191 /// This method can be used for string data that is _terminated_,
1192 /// rather than _separated_ by a pattern.
1194 /// # Iterator behavior
1196 /// The returned iterator requires that the pattern supports a
1197 /// reverse search, and it will be double ended if a forward/reverse
1198 /// search yields the same elements.
1200 /// For iterating from the front, the [`split_terminator`] method can be
1203 /// [`split_terminator`]: #method.split_terminator
1208 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1209 /// assert_eq!(v, ["B", "A"]);
1211 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1212 /// assert_eq!(v, ["", "B", "", "A"]);
1214 #[stable(feature = "rust1", since = "1.0.0")]
1216 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1217 where P::Searcher: ReverseSearcher<'a>
1219 core_str::StrExt::rsplit_terminator(self, pat)
1222 /// An iterator over substrings of the given string slice, separated by a
1223 /// pattern, restricted to returning at most `n` items.
1225 /// If `n` substrings are returned, the last substring (the `n`th substring)
1226 /// will contain the remainder of the string.
1228 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1231 /// [`char`]: primitive.char.html
1233 /// # Iterator behavior
1235 /// The returned iterator will not be double ended, because it is
1236 /// not efficient to support.
1238 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1241 /// [`rsplitn`]: #method.rsplitn
1245 /// Simple patterns:
1248 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1249 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1251 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1252 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1254 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1255 /// assert_eq!(v, ["abcXdef"]);
1257 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1258 /// assert_eq!(v, [""]);
1261 /// A more complex pattern, using a closure:
1264 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1265 /// assert_eq!(v, ["abc", "defXghi"]);
1267 #[stable(feature = "rust1", since = "1.0.0")]
1269 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1270 core_str::StrExt::splitn(self, n, pat)
1273 /// An iterator over substrings of this string slice, separated by a
1274 /// pattern, starting from the end of the string, restricted to returning
1275 /// at most `n` items.
1277 /// If `n` substrings are returned, the last substring (the `n`th substring)
1278 /// will contain the remainder of the string.
1280 /// The pattern can be a `&str`, [`char`], or a closure that
1281 /// determines the split.
1283 /// [`char`]: primitive.char.html
1285 /// # Iterator behavior
1287 /// The returned iterator will not be double ended, because it is not
1288 /// efficient to support.
1290 /// For splitting from the front, the [`splitn`] method can be used.
1292 /// [`splitn`]: #method.splitn
1296 /// Simple patterns:
1299 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1300 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1302 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1303 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1305 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1306 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1309 /// A more complex pattern, using a closure:
1312 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1313 /// assert_eq!(v, ["ghi", "abc1def"]);
1315 #[stable(feature = "rust1", since = "1.0.0")]
1317 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1318 where P::Searcher: ReverseSearcher<'a>
1320 core_str::StrExt::rsplitn(self, n, pat)
1323 /// An iterator over the disjoint matches of a pattern within the given string
1326 /// The pattern can be a `&str`, [`char`], or a closure that
1327 /// determines if a character matches.
1329 /// [`char`]: primitive.char.html
1331 /// # Iterator behavior
1333 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1334 /// allows a reverse search and forward/reverse search yields the same
1335 /// elements. This is true for, eg, [`char`] but not for `&str`.
1337 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1338 /// [`char`]: primitive.char.html
1340 /// If the pattern allows a reverse search but its results might differ
1341 /// from a forward search, the [`rmatches`] method can be used.
1343 /// [`rmatches`]: #method.rmatches
1350 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1351 /// assert_eq!(v, ["abc", "abc", "abc"]);
1353 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1354 /// assert_eq!(v, ["1", "2", "3"]);
1356 #[stable(feature = "str_matches", since = "1.2.0")]
1358 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1359 core_str::StrExt::matches(self, pat)
1362 /// An iterator over the disjoint matches of a pattern within this string slice,
1363 /// yielded in reverse order.
1365 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1366 /// a character matches.
1368 /// [`char`]: primitive.char.html
1370 /// # Iterator behavior
1372 /// The returned iterator requires that the pattern supports a reverse
1373 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1374 /// search yields the same elements.
1376 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1378 /// For iterating from the front, the [`matches`] method can be used.
1380 /// [`matches`]: #method.matches
1387 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1388 /// assert_eq!(v, ["abc", "abc", "abc"]);
1390 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1391 /// assert_eq!(v, ["3", "2", "1"]);
1393 #[stable(feature = "str_matches", since = "1.2.0")]
1395 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1396 where P::Searcher: ReverseSearcher<'a>
1398 core_str::StrExt::rmatches(self, pat)
1401 /// An iterator over the disjoint matches of a pattern within this string
1402 /// slice as well as the index that the match starts at.
1404 /// For matches of `pat` within `self` that overlap, only the indices
1405 /// corresponding to the first match are returned.
1407 /// The pattern can be a `&str`, [`char`], or a closure that determines
1408 /// if a character matches.
1410 /// [`char`]: primitive.char.html
1412 /// # Iterator behavior
1414 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1415 /// allows a reverse search and forward/reverse search yields the same
1416 /// elements. This is true for, eg, [`char`] but not for `&str`.
1418 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1420 /// If the pattern allows a reverse search but its results might differ
1421 /// from a forward search, the [`rmatch_indices`] method can be used.
1423 /// [`rmatch_indices`]: #method.rmatch_indices
1430 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1431 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1433 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1434 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1436 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1437 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1439 #[stable(feature = "str_match_indices", since = "1.5.0")]
1441 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1442 core_str::StrExt::match_indices(self, pat)
1445 /// An iterator over the disjoint matches of a pattern within `self`,
1446 /// yielded in reverse order along with the index of the match.
1448 /// For matches of `pat` within `self` that overlap, only the indices
1449 /// corresponding to the last match are returned.
1451 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1452 /// character matches.
1454 /// [`char`]: primitive.char.html
1456 /// # Iterator behavior
1458 /// The returned iterator requires that the pattern supports a reverse
1459 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1460 /// search yields the same elements.
1462 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1464 /// For iterating from the front, the [`match_indices`] method can be used.
1466 /// [`match_indices`]: #method.match_indices
1473 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1474 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1476 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1477 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1479 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1480 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1482 #[stable(feature = "str_match_indices", since = "1.5.0")]
1484 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1485 where P::Searcher: ReverseSearcher<'a>
1487 core_str::StrExt::rmatch_indices(self, pat)
1490 /// Returns a string slice with leading and trailing whitespace removed.
1492 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1493 /// Core Property `White_Space`.
1500 /// let s = " Hello\tworld\t";
1502 /// assert_eq!("Hello\tworld", s.trim());
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 pub fn trim(&self) -> &str {
1506 UnicodeStr::trim(self)
1509 /// Returns a string slice with leading whitespace removed.
1511 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1512 /// Core Property `White_Space`.
1514 /// # Text directionality
1516 /// A string is a sequence of bytes. 'Left' in this context means the first
1517 /// position of that byte string; for a language like Arabic or Hebrew
1518 /// which are 'right to left' rather than 'left to right', this will be
1519 /// the _right_ side, not the left.
1526 /// let s = " Hello\tworld\t";
1528 /// assert_eq!("Hello\tworld\t", s.trim_left());
1534 /// let s = " English";
1535 /// assert!(Some('E') == s.trim_left().chars().next());
1537 /// let s = " עברית";
1538 /// assert!(Some('ע') == s.trim_left().chars().next());
1540 #[stable(feature = "rust1", since = "1.0.0")]
1541 pub fn trim_left(&self) -> &str {
1542 UnicodeStr::trim_left(self)
1545 /// Returns a string slice with trailing whitespace removed.
1547 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1548 /// Core Property `White_Space`.
1550 /// # Text directionality
1552 /// A string is a sequence of bytes. 'Right' in this context means the last
1553 /// position of that byte string; for a language like Arabic or Hebrew
1554 /// which are 'right to left' rather than 'left to right', this will be
1555 /// the _left_ side, not the right.
1562 /// let s = " Hello\tworld\t";
1564 /// assert_eq!(" Hello\tworld", s.trim_right());
1570 /// let s = "English ";
1571 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1573 /// let s = "עברית ";
1574 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1576 #[stable(feature = "rust1", since = "1.0.0")]
1577 pub fn trim_right(&self) -> &str {
1578 UnicodeStr::trim_right(self)
1581 /// Returns a string slice with all prefixes and suffixes that match a
1582 /// pattern repeatedly removed.
1584 /// The pattern can be a [`char`] or a closure that determines if a
1585 /// character matches.
1587 /// [`char`]: primitive.char.html
1591 /// Simple patterns:
1594 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1595 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1597 /// let x: &[_] = &['1', '2'];
1598 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1601 /// A more complex pattern, using a closure:
1604 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1608 where P::Searcher: DoubleEndedSearcher<'a>
1610 core_str::StrExt::trim_matches(self, pat)
1613 /// Returns a string slice with all prefixes that match a pattern
1614 /// repeatedly removed.
1616 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1617 /// a character matches.
1619 /// [`char`]: primitive.char.html
1621 /// # Text directionality
1623 /// A string is a sequence of bytes. 'Left' in this context means the first
1624 /// position of that byte string; for a language like Arabic or Hebrew
1625 /// which are 'right to left' rather than 'left to right', this will be
1626 /// the _right_ side, not the left.
1633 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1634 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1636 /// let x: &[_] = &['1', '2'];
1637 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1641 core_str::StrExt::trim_left_matches(self, pat)
1644 /// Returns a string slice with all suffixes that match a pattern
1645 /// repeatedly removed.
1647 /// The pattern can be a `&str`, [`char`], or a closure that
1648 /// determines if a character matches.
1650 /// [`char`]: primitive.char.html
1652 /// # Text directionality
1654 /// A string is a sequence of bytes. 'Right' in this context means the last
1655 /// position of that byte string; for a language like Arabic or Hebrew
1656 /// which are 'right to left' rather than 'left to right', this will be
1657 /// the _left_ side, not the right.
1661 /// Simple patterns:
1664 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1665 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1667 /// let x: &[_] = &['1', '2'];
1668 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1671 /// A more complex pattern, using a closure:
1674 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1676 #[stable(feature = "rust1", since = "1.0.0")]
1677 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1678 where P::Searcher: ReverseSearcher<'a>
1680 core_str::StrExt::trim_right_matches(self, pat)
1683 /// Parses this string slice into another type.
1685 /// Because `parse` is so general, it can cause problems with type
1686 /// inference. As such, `parse` is one of the few times you'll see
1687 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1688 /// helps the inference algorithm understand specifically which type
1689 /// you're trying to parse into.
1691 /// `parse` can parse any type that implements the [`FromStr`] trait.
1693 /// [`FromStr`]: str/trait.FromStr.html
1697 /// Will return [`Err`] if it's not possible to parse this string slice into
1698 /// the desired type.
1700 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1707 /// let four: u32 = "4".parse().unwrap();
1709 /// assert_eq!(4, four);
1712 /// Using the 'turbofish' instead of annotating `four`:
1715 /// let four = "4".parse::<u32>();
1717 /// assert_eq!(Ok(4), four);
1720 /// Failing to parse:
1723 /// let nope = "j".parse::<u32>();
1725 /// assert!(nope.is_err());
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1730 core_str::StrExt::parse(self)
1733 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
1734 #[unstable(feature = "str_box_extras", issue = "41119")]
1735 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
1739 /// Replaces all matches of a pattern with another string.
1741 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1742 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1743 /// replaces them with the replacement string slice.
1745 /// [`String`]: string/struct.String.html
1752 /// let s = "this is old";
1754 /// assert_eq!("this is new", s.replace("old", "new"));
1757 /// When the pattern doesn't match:
1760 /// let s = "this is old";
1761 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1763 #[stable(feature = "rust1", since = "1.0.0")]
1765 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1766 let mut result = String::new();
1767 let mut last_end = 0;
1768 for (start, part) in self.match_indices(from) {
1769 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1770 result.push_str(to);
1771 last_end = start + part.len();
1773 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1777 /// Replaces first N matches of a pattern with another string.
1779 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1780 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1781 /// replaces them with the replacement string slice at most `count` times.
1783 /// [`String`]: string/struct.String.html
1790 /// let s = "foo foo 123 foo";
1791 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1792 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1793 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1796 /// When the pattern doesn't match:
1799 /// let s = "this is old";
1800 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1802 #[stable(feature = "str_replacen", since = "1.16.0")]
1803 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1804 // Hope to reduce the times of re-allocation
1805 let mut result = String::with_capacity(32);
1806 let mut last_end = 0;
1807 for (start, part) in self.match_indices(pat).take(count) {
1808 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1809 result.push_str(to);
1810 last_end = start + part.len();
1812 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1816 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1818 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1821 /// Since some characters can expand into multiple characters when changing
1822 /// the case, this function returns a [`String`] instead of modifying the
1823 /// parameter in-place.
1825 /// [`String`]: string/struct.String.html
1832 /// let s = "HELLO";
1834 /// assert_eq!("hello", s.to_lowercase());
1837 /// A tricky example, with sigma:
1840 /// let sigma = "Σ";
1842 /// assert_eq!("σ", sigma.to_lowercase());
1844 /// // but at the end of a word, it's ς, not σ:
1845 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1847 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1850 /// Languages without case are not changed:
1853 /// let new_year = "农历新年";
1855 /// assert_eq!(new_year, new_year.to_lowercase());
1857 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1858 pub fn to_lowercase(&self) -> String {
1859 let mut s = String::with_capacity(self.len());
1860 for (i, c) in self[..].char_indices() {
1862 // Σ maps to σ, except at the end of a word where it maps to ς.
1863 // This is the only conditional (contextual) but language-independent mapping
1864 // in `SpecialCasing.txt`,
1865 // so hard-code it rather than have a generic "condition" mechanism.
1866 // See https://github.com/rust-lang/rust/issues/26035
1867 map_uppercase_sigma(self, i, &mut s)
1869 s.extend(c.to_lowercase());
1874 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1875 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1876 // for the definition of `Final_Sigma`.
1877 debug_assert!('Σ'.len_utf8() == 2);
1878 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1879 !case_ignoreable_then_cased(from[i + 2..].chars());
1880 to.push_str(if is_word_final { "ς" } else { "σ" });
1883 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1884 use std_unicode::derived_property::{Cased, Case_Ignorable};
1885 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1886 Some(c) => Cased(c),
1892 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1894 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1897 /// Since some characters can expand into multiple characters when changing
1898 /// the case, this function returns a [`String`] instead of modifying the
1899 /// parameter in-place.
1901 /// [`String`]: string/struct.String.html
1908 /// let s = "hello";
1910 /// assert_eq!("HELLO", s.to_uppercase());
1913 /// Scripts without case are not changed:
1916 /// let new_year = "农历新年";
1918 /// assert_eq!(new_year, new_year.to_uppercase());
1920 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1921 pub fn to_uppercase(&self) -> String {
1922 let mut s = String::with_capacity(self.len());
1923 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1927 /// Escapes each char in `s` with [`char::escape_debug`].
1929 /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
1930 #[unstable(feature = "str_escape",
1931 reason = "return type may change to be an iterator",
1933 pub fn escape_debug(&self) -> String {
1934 self.chars().flat_map(|c| c.escape_debug()).collect()
1937 /// Escapes each char in `s` with [`char::escape_default`].
1939 /// [`char::escape_default`]: primitive.char.html#method.escape_default
1940 #[unstable(feature = "str_escape",
1941 reason = "return type may change to be an iterator",
1943 pub fn escape_default(&self) -> String {
1944 self.chars().flat_map(|c| c.escape_default()).collect()
1947 /// Escapes each char in `s` with [`char::escape_unicode`].
1949 /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
1950 #[unstable(feature = "str_escape",
1951 reason = "return type may change to be an iterator",
1953 pub fn escape_unicode(&self) -> String {
1954 self.chars().flat_map(|c| c.escape_unicode()).collect()
1957 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
1959 /// [`String`]: string/struct.String.html
1960 /// [`Box<str>`]: boxed/struct.Box.html
1967 /// let string = String::from("birthday gift");
1968 /// let boxed_str = string.clone().into_boxed_str();
1970 /// assert_eq!(boxed_str.into_string(), string);
1972 #[stable(feature = "box_str", since = "1.4.0")]
1973 pub fn into_string(self: Box<str>) -> String {
1975 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1976 String::from_utf8_unchecked(slice.into_vec())
1980 /// Create a [`String`] by repeating a string `n` times.
1982 /// [`String`]: string/struct.String.html
1989 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
1991 #[stable(feature = "repeat_str", since = "1.16.0")]
1992 pub fn repeat(&self, n: usize) -> String {
1993 let mut s = String::with_capacity(self.len() * n);
1994 s.extend((0..n).map(|_| self));