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, Chars, CharIndices, Bytes};
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub use core::str::{from_utf8_unchecked, 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;
81 #[unstable(feature = "slice_concat_ext",
82 reason = "trait should not have to exist",
84 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
87 fn concat(&self) -> String {
92 // `len` calculation may overflow but push_str will check boundaries
93 let len = self.iter().map(|s| s.borrow().len()).sum();
94 let mut result = String::with_capacity(len);
97 result.push_str(s.borrow())
103 fn join(&self, sep: &str) -> String {
105 return String::new();
110 return self.concat();
113 // this is wrong without the guarantee that `self` is non-empty
114 // `len` calculation may overflow but push_str but will check boundaries
115 let len = sep.len() * (self.len() - 1) +
116 self.iter().map(|s| s.borrow().len()).sum::<usize>();
117 let mut result = String::with_capacity(len);
118 let mut first = true;
124 result.push_str(sep);
126 result.push_str(s.borrow());
131 fn connect(&self, sep: &str) -> String {
136 /// An iterator of [`u16`] over the string encoded as UTF-16.
138 /// [`u16`]: ../../std/primitive.u16.html
140 /// This struct is created by the [`encode_utf16`] method on [`str`].
141 /// See its documentation for more.
143 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
144 /// [`str`]: ../../std/primitive.str.html
146 #[stable(feature = "encode_utf16", since = "1.8.0")]
147 pub struct EncodeUtf16<'a> {
148 encoder: Utf16Encoder<Chars<'a>>,
151 #[stable(feature = "collection_debug", since = "1.17.0")]
152 impl<'a> fmt::Debug for EncodeUtf16<'a> {
153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154 f.pad("EncodeUtf16 { .. }")
158 #[stable(feature = "encode_utf16", since = "1.8.0")]
159 impl<'a> Iterator for EncodeUtf16<'a> {
163 fn next(&mut self) -> Option<u16> {
168 fn size_hint(&self) -> (usize, Option<usize>) {
169 self.encoder.size_hint()
173 #[unstable(feature = "fused", issue = "35602")]
174 impl<'a> FusedIterator for EncodeUtf16<'a> {}
176 // Return the initial codepoint accumulator for the first byte.
177 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
178 // for width 3, and 3 bits for width 4
179 macro_rules! utf8_first_byte {
180 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
183 // return the value of $ch updated with continuation byte $byte
184 macro_rules! utf8_acc_cont_byte {
185 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
188 #[stable(feature = "rust1", since = "1.0.0")]
189 impl Borrow<str> for String {
191 fn borrow(&self) -> &str {
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl ToOwned for str {
199 fn to_owned(&self) -> String {
200 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
204 /// Methods for string slices.
208 /// Returns the length of `self`.
210 /// This length is in bytes, not [`char`]s or graphemes. In other words,
211 /// it may not be what a human considers the length of the string.
213 /// [`char`]: primitive.char.html
220 /// let len = "foo".len();
221 /// assert_eq!(3, len);
223 /// let len = "ƒoo".len(); // fancy f!
224 /// assert_eq!(4, len);
226 #[stable(feature = "rust1", since = "1.0.0")]
228 pub fn len(&self) -> usize {
229 core_str::StrExt::len(self)
232 /// Returns `true` if `self` has a length of zero bytes.
240 /// assert!(s.is_empty());
242 /// let s = "not empty";
243 /// assert!(!s.is_empty());
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub fn is_empty(&self) -> bool {
248 core_str::StrExt::is_empty(self)
251 /// Checks that `index`-th byte lies at the start and/or end of a
252 /// UTF-8 code point sequence.
254 /// The start and end of the string (when `index == self.len()`) are
258 /// Returns `false` if `index` is greater than `self.len()`.
263 /// let s = "Löwe 老虎 Léopard";
264 /// assert!(s.is_char_boundary(0));
266 /// assert!(s.is_char_boundary(6));
267 /// assert!(s.is_char_boundary(s.len()));
269 /// // second byte of `ö`
270 /// assert!(!s.is_char_boundary(2));
272 /// // third byte of `老`
273 /// assert!(!s.is_char_boundary(8));
275 #[stable(feature = "is_char_boundary", since = "1.9.0")]
277 pub fn is_char_boundary(&self, index: usize) -> bool {
278 core_str::StrExt::is_char_boundary(self, index)
281 /// Converts a string slice to a byte slice.
288 /// let bytes = "bors".as_bytes();
289 /// assert_eq!(b"bors", bytes);
291 #[stable(feature = "rust1", since = "1.0.0")]
293 pub fn as_bytes(&self) -> &[u8] {
294 core_str::StrExt::as_bytes(self)
297 /// Converts a string slice to a raw pointer.
299 /// As string slices are a slice of bytes, the raw pointer points to a
300 /// [`u8`]. This pointer will be pointing to the first byte of the string
303 /// [`u8`]: primitive.u8.html
311 /// let ptr = s.as_ptr();
313 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn as_ptr(&self) -> *const u8 {
316 core_str::StrExt::as_ptr(self)
319 /// Returns a subslice of `str`.
321 /// This is the non-panicking alternative to indexing the `str`. Returns `None` whenever
322 /// equivalent indexing operation would panic.
327 /// # #![feature(str_checked_slicing)]
329 /// assert_eq!(Some("🗻"), v.get(0..4));
330 /// assert!(v.get(1..).is_none());
331 /// assert!(v.get(..8).is_none());
332 /// assert!(v.get(..42).is_none());
334 #[unstable(feature = "str_checked_slicing", issue = "39932")]
336 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
337 core_str::StrExt::get(self, i)
340 /// Returns a mutable subslice of `str`.
342 /// This is the non-panicking alternative to indexing the `str`. Returns `None` whenever
343 /// equivalent indexing operation would panic.
348 /// # #![feature(str_checked_slicing)]
349 /// let mut v = String::from("🗻∈🌏");
350 /// assert_eq!(Some("🗻"), v.get_mut(0..4).map(|v| &*v));
351 /// assert!(v.get_mut(1..).is_none());
352 /// assert!(v.get_mut(..8).is_none());
353 /// assert!(v.get_mut(..42).is_none());
355 #[unstable(feature = "str_checked_slicing", issue = "39932")]
357 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
358 core_str::StrExt::get_mut(self, i)
361 /// Returns a unchecked subslice of `str`.
363 /// This is the unchecked alternative to indexing the `str`.
367 /// Callers of this function are responsible that these preconditions are
370 /// * The starting index must come before the ending index;
371 /// * Indexes must be within bounds of the original slice;
372 /// * Indexes must lie on UTF-8 sequence boundaries.
374 /// Failing that, the returned string slice may reference invalid memory or
375 /// violate the invariants communicated by the `str` type.
380 /// # #![feature(str_checked_slicing)]
383 /// assert_eq!("🗻", v.get_unchecked(0..4));
384 /// assert_eq!("∈", v.get_unchecked(4..7));
385 /// assert_eq!("🌏", v.get_unchecked(7..11));
388 #[unstable(feature = "str_checked_slicing", issue = "39932")]
390 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
391 core_str::StrExt::get_unchecked(self, i)
394 /// Returns a mutable, unchecked subslice of `str`.
396 /// This is the unchecked alternative to indexing the `str`.
400 /// Callers of this function are responsible that these preconditions are
403 /// * The starting index must come before the ending index;
404 /// * Indexes must be within bounds of the original slice;
405 /// * Indexes must lie on UTF-8 sequence boundaries.
407 /// Failing that, the returned string slice may reference invalid memory or
408 /// violate the invariants communicated by the `str` type.
413 /// # #![feature(str_checked_slicing)]
414 /// let mut v = String::from("🗻∈🌏");
416 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
417 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
418 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
421 #[unstable(feature = "str_checked_slicing", issue = "39932")]
423 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
424 core_str::StrExt::get_unchecked_mut(self, i)
427 /// Creates a string slice from another string slice, bypassing safety
430 /// This new slice goes from `begin` to `end`, including `begin` but
433 /// To get a mutable string slice instead, see the
434 /// [`slice_mut_unchecked`] method.
436 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
440 /// Callers of this function are responsible that three preconditions are
443 /// * `begin` must come before `end`.
444 /// * `begin` and `end` must be byte positions within the string slice.
445 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
452 /// let s = "Löwe 老虎 Léopard";
455 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
458 /// let s = "Hello, world!";
461 /// assert_eq!("world", s.slice_unchecked(7, 12));
464 #[stable(feature = "rust1", since = "1.0.0")]
466 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
467 core_str::StrExt::slice_unchecked(self, begin, end)
470 /// Creates a string slice from another string slice, bypassing safety
473 /// This new slice goes from `begin` to `end`, including `begin` but
476 /// To get an immutable string slice instead, see the
477 /// [`slice_unchecked`] method.
479 /// [`slice_unchecked`]: #method.slice_unchecked
483 /// Callers of this function are responsible that three preconditions are
486 /// * `begin` must come before `end`.
487 /// * `begin` and `end` must be byte positions within the string slice.
488 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
489 #[stable(feature = "str_slice_mut", since = "1.5.0")]
491 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
492 core_str::StrExt::slice_mut_unchecked(self, begin, end)
495 /// Divide one string slice into two at an index.
497 /// The argument, `mid`, should be a byte offset from the start of the
498 /// string. It must also be on the boundary of a UTF-8 code point.
500 /// The two slices returned go from the start of the string slice to `mid`,
501 /// and from `mid` to the end of the string slice.
503 /// To get mutable string slices instead, see the [`split_at_mut`]
506 /// [`split_at_mut`]: #method.split_at_mut
510 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
511 /// beyond the last code point of the string slice.
518 /// let s = "Per Martin-Löf";
520 /// let (first, last) = s.split_at(3);
522 /// assert_eq!("Per", first);
523 /// assert_eq!(" Martin-Löf", last);
526 #[stable(feature = "str_split_at", since = "1.4.0")]
527 pub fn split_at(&self, mid: usize) -> (&str, &str) {
528 core_str::StrExt::split_at(self, mid)
531 /// Divide one mutable string slice into two at an index.
533 /// The argument, `mid`, should be a byte offset from the start of the
534 /// string. It must also be on the boundary of a UTF-8 code point.
536 /// The two slices returned go from the start of the string slice to `mid`,
537 /// and from `mid` to the end of the string slice.
539 /// To get immutable string slices instead, see the [`split_at`] method.
541 /// [`split_at`]: #method.split_at
545 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
546 /// beyond the last code point of the string slice.
553 /// let mut s = "Per Martin-Löf".to_string();
555 /// let (first, last) = s.split_at_mut(3);
557 /// assert_eq!("Per", first);
558 /// assert_eq!(" Martin-Löf", last);
561 #[stable(feature = "str_split_at", since = "1.4.0")]
562 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
563 core_str::StrExt::split_at_mut(self, mid)
566 /// Returns an iterator over the `char`s of a string slice.
568 /// As a string slice consists of valid UTF-8, we can iterate through a
569 /// string slice by [`char`]. This method returns such an iterator.
571 /// It's important to remember that [`char`] represents a Unicode Scalar
572 /// Value, and may not match your idea of what a 'character' is. Iteration
573 /// over grapheme clusters may be what you actually want.
575 /// [`char`]: primitive.char.html
582 /// let word = "goodbye";
584 /// let count = word.chars().count();
585 /// assert_eq!(7, count);
587 /// let mut chars = word.chars();
589 /// assert_eq!(Some('g'), chars.next());
590 /// assert_eq!(Some('o'), chars.next());
591 /// assert_eq!(Some('o'), chars.next());
592 /// assert_eq!(Some('d'), chars.next());
593 /// assert_eq!(Some('b'), chars.next());
594 /// assert_eq!(Some('y'), chars.next());
595 /// assert_eq!(Some('e'), chars.next());
597 /// assert_eq!(None, chars.next());
600 /// Remember, [`char`]s may not match your human intuition about characters:
605 /// let mut chars = y.chars();
607 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
608 /// assert_eq!(Some('\u{0306}'), chars.next());
610 /// assert_eq!(None, chars.next());
612 #[stable(feature = "rust1", since = "1.0.0")]
614 pub fn chars(&self) -> Chars {
615 core_str::StrExt::chars(self)
617 /// Returns an iterator over the [`char`]s of a string slice, and their
620 /// As a string slice consists of valid UTF-8, we can iterate through a
621 /// string slice by [`char`]. This method returns an iterator of both
622 /// these [`char`]s, as well as their byte positions.
624 /// The iterator yields tuples. The position is first, the [`char`] is
627 /// [`char`]: primitive.char.html
634 /// let word = "goodbye";
636 /// let count = word.char_indices().count();
637 /// assert_eq!(7, count);
639 /// let mut char_indices = word.char_indices();
641 /// assert_eq!(Some((0, 'g')), char_indices.next());
642 /// assert_eq!(Some((1, 'o')), char_indices.next());
643 /// assert_eq!(Some((2, 'o')), char_indices.next());
644 /// assert_eq!(Some((3, 'd')), char_indices.next());
645 /// assert_eq!(Some((4, 'b')), char_indices.next());
646 /// assert_eq!(Some((5, 'y')), char_indices.next());
647 /// assert_eq!(Some((6, 'e')), char_indices.next());
649 /// assert_eq!(None, char_indices.next());
652 /// Remember, [`char`]s may not match your human intuition about characters:
657 /// let mut char_indices = y.char_indices();
659 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
660 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
662 /// assert_eq!(None, char_indices.next());
664 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn char_indices(&self) -> CharIndices {
667 core_str::StrExt::char_indices(self)
670 /// An iterator over the bytes of a string slice.
672 /// As a string slice consists of a sequence of bytes, we can iterate
673 /// through a string slice by byte. This method returns such an iterator.
680 /// let mut bytes = "bors".bytes();
682 /// assert_eq!(Some(b'b'), bytes.next());
683 /// assert_eq!(Some(b'o'), bytes.next());
684 /// assert_eq!(Some(b'r'), bytes.next());
685 /// assert_eq!(Some(b's'), bytes.next());
687 /// assert_eq!(None, bytes.next());
689 #[stable(feature = "rust1", since = "1.0.0")]
691 pub fn bytes(&self) -> Bytes {
692 core_str::StrExt::bytes(self)
695 /// Split a string slice by whitespace.
697 /// The iterator returned will return string slices that are sub-slices of
698 /// the original string slice, separated by any amount of whitespace.
700 /// 'Whitespace' is defined according to the terms of the Unicode Derived
701 /// Core Property `White_Space`.
708 /// let mut iter = "A few words".split_whitespace();
710 /// assert_eq!(Some("A"), iter.next());
711 /// assert_eq!(Some("few"), iter.next());
712 /// assert_eq!(Some("words"), iter.next());
714 /// assert_eq!(None, iter.next());
717 /// All kinds of whitespace are considered:
720 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
721 /// assert_eq!(Some("Mary"), iter.next());
722 /// assert_eq!(Some("had"), iter.next());
723 /// assert_eq!(Some("a"), iter.next());
724 /// assert_eq!(Some("little"), iter.next());
725 /// assert_eq!(Some("lamb"), iter.next());
727 /// assert_eq!(None, iter.next());
729 #[stable(feature = "split_whitespace", since = "1.1.0")]
731 pub fn split_whitespace(&self) -> SplitWhitespace {
732 UnicodeStr::split_whitespace(self)
735 /// An iterator over the lines of a string, as string slices.
737 /// Lines are ended with either a newline (`\n`) or a carriage return with
738 /// a line feed (`\r\n`).
740 /// The final line ending is optional.
747 /// let text = "foo\r\nbar\n\nbaz\n";
748 /// let mut lines = text.lines();
750 /// assert_eq!(Some("foo"), lines.next());
751 /// assert_eq!(Some("bar"), lines.next());
752 /// assert_eq!(Some(""), lines.next());
753 /// assert_eq!(Some("baz"), lines.next());
755 /// assert_eq!(None, lines.next());
758 /// The final line ending isn't required:
761 /// let text = "foo\nbar\n\r\nbaz";
762 /// let mut lines = text.lines();
764 /// assert_eq!(Some("foo"), lines.next());
765 /// assert_eq!(Some("bar"), lines.next());
766 /// assert_eq!(Some(""), lines.next());
767 /// assert_eq!(Some("baz"), lines.next());
769 /// assert_eq!(None, lines.next());
771 #[stable(feature = "rust1", since = "1.0.0")]
773 pub fn lines(&self) -> Lines {
774 core_str::StrExt::lines(self)
777 /// An iterator over the lines of a string.
778 #[stable(feature = "rust1", since = "1.0.0")]
779 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
782 pub fn lines_any(&self) -> LinesAny {
783 core_str::StrExt::lines_any(self)
786 /// Returns an iterator of `u16` over the string encoded as UTF-16.
787 #[stable(feature = "encode_utf16", since = "1.8.0")]
788 pub fn encode_utf16(&self) -> EncodeUtf16 {
789 EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
792 /// Returns `true` if the given pattern matches a sub-slice of
793 /// this string slice.
795 /// Returns `false` if it does not.
802 /// let bananas = "bananas";
804 /// assert!(bananas.contains("nana"));
805 /// assert!(!bananas.contains("apples"));
807 #[stable(feature = "rust1", since = "1.0.0")]
808 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
809 core_str::StrExt::contains(self, pat)
812 /// Returns `true` if the given pattern matches a prefix of this
815 /// Returns `false` if it does not.
822 /// let bananas = "bananas";
824 /// assert!(bananas.starts_with("bana"));
825 /// assert!(!bananas.starts_with("nana"));
827 #[stable(feature = "rust1", since = "1.0.0")]
828 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
829 core_str::StrExt::starts_with(self, pat)
832 /// Returns `true` if the given pattern matches a suffix of this
835 /// Returns `false` if it does not.
842 /// let bananas = "bananas";
844 /// assert!(bananas.ends_with("anas"));
845 /// assert!(!bananas.ends_with("nana"));
847 #[stable(feature = "rust1", since = "1.0.0")]
848 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
849 where P::Searcher: ReverseSearcher<'a>
851 core_str::StrExt::ends_with(self, pat)
854 /// Returns the byte index of the first character of this string slice that
855 /// matches the pattern.
857 /// Returns [`None`] if the pattern doesn't match.
859 /// The pattern can be a `&str`, [`char`], or a closure that determines if
860 /// a character matches.
862 /// [`char`]: primitive.char.html
863 /// [`None`]: option/enum.Option.html#variant.None
870 /// let s = "Löwe 老虎 Léopard";
872 /// assert_eq!(s.find('L'), Some(0));
873 /// assert_eq!(s.find('é'), Some(14));
874 /// assert_eq!(s.find("Léopard"), Some(13));
877 /// More complex patterns with closures:
880 /// let s = "Löwe 老虎 Léopard";
882 /// assert_eq!(s.find(char::is_whitespace), Some(5));
883 /// assert_eq!(s.find(char::is_lowercase), Some(1));
886 /// Not finding the pattern:
889 /// let s = "Löwe 老虎 Léopard";
890 /// let x: &[_] = &['1', '2'];
892 /// assert_eq!(s.find(x), None);
894 #[stable(feature = "rust1", since = "1.0.0")]
895 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
896 core_str::StrExt::find(self, pat)
899 /// Returns the byte index of the last character of this string slice that
900 /// matches the pattern.
902 /// Returns [`None`] if the pattern doesn't match.
904 /// The pattern can be a `&str`, [`char`], or a closure that determines if
905 /// a character matches.
907 /// [`char`]: primitive.char.html
908 /// [`None`]: option/enum.Option.html#variant.None
915 /// let s = "Löwe 老虎 Léopard";
917 /// assert_eq!(s.rfind('L'), Some(13));
918 /// assert_eq!(s.rfind('é'), Some(14));
921 /// More complex patterns with closures:
924 /// let s = "Löwe 老虎 Léopard";
926 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
927 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
930 /// Not finding the pattern:
933 /// let s = "Löwe 老虎 Léopard";
934 /// let x: &[_] = &['1', '2'];
936 /// assert_eq!(s.rfind(x), None);
938 #[stable(feature = "rust1", since = "1.0.0")]
939 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
940 where P::Searcher: ReverseSearcher<'a>
942 core_str::StrExt::rfind(self, pat)
945 /// An iterator over substrings of this string slice, separated by
946 /// characters matched by a pattern.
948 /// The pattern can be a `&str`, [`char`], or a closure that determines the
951 /// # Iterator behavior
953 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
954 /// allows a reverse search and forward/reverse search yields the same
955 /// elements. This is true for, eg, [`char`] but not for `&str`.
957 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
959 /// If the pattern allows a reverse search but its results might differ
960 /// from a forward search, the [`rsplit`] method can be used.
962 /// [`char`]: primitive.char.html
963 /// [`rsplit`]: #method.rsplit
970 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
971 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
973 /// let v: Vec<&str> = "".split('X').collect();
974 /// assert_eq!(v, [""]);
976 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
977 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
979 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
980 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
982 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
983 /// assert_eq!(v, ["abc", "def", "ghi"]);
985 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
986 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
989 /// A more complex pattern, using a closure:
992 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
993 /// assert_eq!(v, ["abc", "def", "ghi"]);
996 /// If a string contains multiple contiguous separators, you will end up
997 /// with empty strings in the output:
1000 /// let x = "||||a||b|c".to_string();
1001 /// let d: Vec<_> = x.split('|').collect();
1003 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1006 /// Contiguous separators are separated by the empty string.
1009 /// let x = "(///)".to_string();
1010 /// let d: Vec<_> = x.split('/').collect();;
1012 /// assert_eq!(d, &["(", "", "", ")"]);
1015 /// Separators at the start or end of a string are neighbored
1016 /// by empty strings.
1019 /// let d: Vec<_> = "010".split("0").collect();
1020 /// assert_eq!(d, &["", "1", ""]);
1023 /// When the empty string is used as a separator, it separates
1024 /// every character in the string, along with the beginning
1025 /// and end of the string.
1028 /// let f: Vec<_> = "rust".split("").collect();
1029 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1032 /// Contiguous separators can lead to possibly surprising behavior
1033 /// when whitespace is used as the separator. This code is correct:
1036 /// let x = " a b c".to_string();
1037 /// let d: Vec<_> = x.split(' ').collect();
1039 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1042 /// It does _not_ give you:
1045 /// assert_eq!(d, &["a", "b", "c"]);
1048 /// Use [`split_whitespace`] for this behavior.
1050 /// [`split_whitespace`]: #method.split_whitespace
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1053 core_str::StrExt::split(self, pat)
1056 /// An iterator over substrings of the given string slice, separated by
1057 /// characters matched by a pattern and yielded in reverse order.
1059 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1062 /// [`char`]: primitive.char.html
1064 /// # Iterator behavior
1066 /// The returned iterator requires that the pattern supports a reverse
1067 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1068 /// search yields the same elements.
1070 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1072 /// For iterating from the front, the [`split`] method can be used.
1074 /// [`split`]: #method.split
1078 /// Simple patterns:
1081 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1082 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1084 /// let v: Vec<&str> = "".rsplit('X').collect();
1085 /// assert_eq!(v, [""]);
1087 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1088 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1090 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1091 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1094 /// A more complex pattern, using a closure:
1097 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1098 /// assert_eq!(v, ["ghi", "def", "abc"]);
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1102 where P::Searcher: ReverseSearcher<'a>
1104 core_str::StrExt::rsplit(self, pat)
1107 /// An iterator over substrings of the given string slice, separated by
1108 /// characters matched by a pattern.
1110 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1113 /// Equivalent to [`split`], except that the trailing substring
1114 /// is skipped if empty.
1116 /// [`split`]: #method.split
1118 /// This method can be used for string data that is _terminated_,
1119 /// rather than _separated_ by a pattern.
1121 /// # Iterator behavior
1123 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1124 /// allows a reverse search and forward/reverse search yields the same
1125 /// elements. This is true for, eg, [`char`] but not for `&str`.
1127 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1128 /// [`char`]: primitive.char.html
1130 /// If the pattern allows a reverse search but its results might differ
1131 /// from a forward search, the [`rsplit_terminator`] method can be used.
1133 /// [`rsplit_terminator`]: #method.rsplit_terminator
1140 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1141 /// assert_eq!(v, ["A", "B"]);
1143 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1144 /// assert_eq!(v, ["A", "", "B", ""]);
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1148 core_str::StrExt::split_terminator(self, pat)
1151 /// An iterator over substrings of `self`, separated by characters
1152 /// matched by a pattern and yielded in reverse order.
1154 /// The pattern can be a simple `&str`, [`char`], or a closure that
1155 /// determines the split.
1156 /// Additional libraries might provide more complex patterns like
1157 /// regular expressions.
1159 /// [`char`]: primitive.char.html
1161 /// Equivalent to [`split`], except that the trailing substring is
1162 /// 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 requires that the pattern supports a
1172 /// reverse search, and it will be double ended if a forward/reverse
1173 /// search yields the same elements.
1175 /// For iterating from the front, the [`split_terminator`] method can be
1178 /// [`split_terminator`]: #method.split_terminator
1183 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1184 /// assert_eq!(v, ["B", "A"]);
1186 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1187 /// assert_eq!(v, ["", "B", "", "A"]);
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1191 where P::Searcher: ReverseSearcher<'a>
1193 core_str::StrExt::rsplit_terminator(self, pat)
1196 /// An iterator over substrings of the given string slice, separated by a
1197 /// pattern, restricted to returning at most `n` items.
1199 /// If `n` substrings are returned, the last substring (the `n`th substring)
1200 /// will contain the remainder of the string.
1202 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1205 /// [`char`]: primitive.char.html
1207 /// # Iterator behavior
1209 /// The returned iterator will not be double ended, because it is
1210 /// not efficient to support.
1212 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1215 /// [`rsplitn`]: #method.rsplitn
1219 /// Simple patterns:
1222 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1223 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1225 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1226 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1228 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1229 /// assert_eq!(v, ["abcXdef"]);
1231 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1232 /// assert_eq!(v, [""]);
1235 /// A more complex pattern, using a closure:
1238 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1239 /// assert_eq!(v, ["abc", "defXghi"]);
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1243 core_str::StrExt::splitn(self, n, pat)
1246 /// An iterator over substrings of this string slice, separated by a
1247 /// pattern, starting from the end of the string, restricted to returning
1248 /// at most `n` items.
1250 /// If `n` substrings are returned, the last substring (the `n`th substring)
1251 /// will contain the remainder of the string.
1253 /// The pattern can be a `&str`, [`char`], or a closure that
1254 /// determines the split.
1256 /// [`char`]: primitive.char.html
1258 /// # Iterator behavior
1260 /// The returned iterator will not be double ended, because it is not
1261 /// efficient to support.
1263 /// For splitting from the front, the [`splitn`] method can be used.
1265 /// [`splitn`]: #method.splitn
1269 /// Simple patterns:
1272 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1273 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1275 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1276 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1278 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1279 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1282 /// A more complex pattern, using a closure:
1285 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1286 /// assert_eq!(v, ["ghi", "abc1def"]);
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1290 where P::Searcher: ReverseSearcher<'a>
1292 core_str::StrExt::rsplitn(self, n, pat)
1295 /// An iterator over the matches of a pattern within the given string
1298 /// The pattern can be a `&str`, [`char`], or a closure that
1299 /// determines if a character matches.
1301 /// [`char`]: primitive.char.html
1303 /// # Iterator behavior
1305 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1306 /// allows a reverse search and forward/reverse search yields the same
1307 /// elements. This is true for, eg, [`char`] but not for `&str`.
1309 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1310 /// [`char`]: primitive.char.html
1312 /// If the pattern allows a reverse search but its results might differ
1313 /// from a forward search, the [`rmatches`] method can be used.
1315 /// [`rmatches`]: #method.rmatches
1322 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1323 /// assert_eq!(v, ["abc", "abc", "abc"]);
1325 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1326 /// assert_eq!(v, ["1", "2", "3"]);
1328 #[stable(feature = "str_matches", since = "1.2.0")]
1329 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1330 core_str::StrExt::matches(self, pat)
1333 /// An iterator over the matches of a pattern within this string slice,
1334 /// yielded in reverse order.
1336 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1337 /// a character matches.
1339 /// [`char`]: primitive.char.html
1341 /// # Iterator behavior
1343 /// The returned iterator requires that the pattern supports a reverse
1344 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1345 /// search yields the same elements.
1347 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1349 /// For iterating from the front, the [`matches`] method can be used.
1351 /// [`matches`]: #method.matches
1358 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1359 /// assert_eq!(v, ["abc", "abc", "abc"]);
1361 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1362 /// assert_eq!(v, ["3", "2", "1"]);
1364 #[stable(feature = "str_matches", since = "1.2.0")]
1365 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1366 where P::Searcher: ReverseSearcher<'a>
1368 core_str::StrExt::rmatches(self, pat)
1371 /// An iterator over the disjoint matches of a pattern within this string
1372 /// slice as well as the index that the match starts at.
1374 /// For matches of `pat` within `self` that overlap, only the indices
1375 /// corresponding to the first match are returned.
1377 /// The pattern can be a `&str`, [`char`], or a closure that determines
1378 /// if a character matches.
1380 /// [`char`]: primitive.char.html
1382 /// # Iterator behavior
1384 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1385 /// allows a reverse search and forward/reverse search yields the same
1386 /// elements. This is true for, eg, [`char`] but not for `&str`.
1388 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1390 /// If the pattern allows a reverse search but its results might differ
1391 /// from a forward search, the [`rmatch_indices`] method can be used.
1393 /// [`rmatch_indices`]: #method.rmatch_indices
1400 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1401 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1403 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1404 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1406 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1407 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1409 #[stable(feature = "str_match_indices", since = "1.5.0")]
1410 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1411 core_str::StrExt::match_indices(self, pat)
1414 /// An iterator over the disjoint matches of a pattern within `self`,
1415 /// yielded in reverse order along with the index of the match.
1417 /// For matches of `pat` within `self` that overlap, only the indices
1418 /// corresponding to the last match are returned.
1420 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1421 /// character matches.
1423 /// [`char`]: primitive.char.html
1425 /// # Iterator behavior
1427 /// The returned iterator requires that the pattern supports a reverse
1428 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1429 /// search yields the same elements.
1431 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1433 /// For iterating from the front, the [`match_indices`] method can be used.
1435 /// [`match_indices`]: #method.match_indices
1442 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1443 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1445 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1446 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1448 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1449 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1451 #[stable(feature = "str_match_indices", since = "1.5.0")]
1452 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1453 where P::Searcher: ReverseSearcher<'a>
1455 core_str::StrExt::rmatch_indices(self, pat)
1458 /// Returns a string slice with leading and trailing whitespace removed.
1460 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1461 /// Core Property `White_Space`.
1468 /// let s = " Hello\tworld\t";
1470 /// assert_eq!("Hello\tworld", s.trim());
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 pub fn trim(&self) -> &str {
1474 UnicodeStr::trim(self)
1477 /// Returns a string slice with leading whitespace removed.
1479 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1480 /// Core Property `White_Space`.
1482 /// # Text directionality
1484 /// A string is a sequence of bytes. 'Left' in this context means the first
1485 /// position of that byte string; for a language like Arabic or Hebrew
1486 /// which are 'right to left' rather than 'left to right', this will be
1487 /// the _right_ side, not the left.
1494 /// let s = " Hello\tworld\t";
1496 /// assert_eq!("Hello\tworld\t", s.trim_left());
1502 /// let s = " English";
1503 /// assert!(Some('E') == s.trim_left().chars().next());
1505 /// let s = " עברית";
1506 /// assert!(Some('ע') == s.trim_left().chars().next());
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 pub fn trim_left(&self) -> &str {
1510 UnicodeStr::trim_left(self)
1513 /// Returns a string slice with trailing whitespace removed.
1515 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1516 /// Core Property `White_Space`.
1518 /// # Text directionality
1520 /// A string is a sequence of bytes. 'Right' in this context means the last
1521 /// position of that byte string; for a language like Arabic or Hebrew
1522 /// which are 'right to left' rather than 'left to right', this will be
1523 /// the _left_ side, not the right.
1530 /// let s = " Hello\tworld\t";
1532 /// assert_eq!(" Hello\tworld", s.trim_right());
1538 /// let s = "English ";
1539 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1541 /// let s = "עברית ";
1542 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 pub fn trim_right(&self) -> &str {
1546 UnicodeStr::trim_right(self)
1549 /// Returns a string slice with all prefixes and suffixes that match a
1550 /// pattern repeatedly removed.
1552 /// The pattern can be a [`char`] or a closure that determines if a
1553 /// character matches.
1555 /// [`char`]: primitive.char.html
1559 /// Simple patterns:
1562 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1563 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1565 /// let x: &[_] = &['1', '2'];
1566 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1569 /// A more complex pattern, using a closure:
1572 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1574 #[stable(feature = "rust1", since = "1.0.0")]
1575 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1576 where P::Searcher: DoubleEndedSearcher<'a>
1578 core_str::StrExt::trim_matches(self, pat)
1581 /// Returns a string slice with all prefixes that match a pattern
1582 /// repeatedly removed.
1584 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1585 /// a character matches.
1587 /// [`char`]: primitive.char.html
1589 /// # Text directionality
1591 /// A string is a sequence of bytes. 'Left' in this context means the first
1592 /// position of that byte string; for a language like Arabic or Hebrew
1593 /// which are 'right to left' rather than 'left to right', this will be
1594 /// the _right_ side, not the left.
1601 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1602 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1604 /// let x: &[_] = &['1', '2'];
1605 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1609 core_str::StrExt::trim_left_matches(self, pat)
1612 /// Returns a string slice with all suffixes that match a pattern
1613 /// repeatedly removed.
1615 /// The pattern can be a `&str`, [`char`], or a closure that
1616 /// determines if a character matches.
1618 /// [`char`]: primitive.char.html
1620 /// # Text directionality
1622 /// A string is a sequence of bytes. 'Right' in this context means the last
1623 /// position of that byte string; for a language like Arabic or Hebrew
1624 /// which are 'right to left' rather than 'left to right', this will be
1625 /// the _left_ side, not the right.
1629 /// Simple patterns:
1632 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1633 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1635 /// let x: &[_] = &['1', '2'];
1636 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1639 /// A more complex pattern, using a closure:
1642 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1646 where P::Searcher: ReverseSearcher<'a>
1648 core_str::StrExt::trim_right_matches(self, pat)
1651 /// Parses this string slice into another type.
1653 /// Because `parse()` is so general, it can cause problems with type
1654 /// inference. As such, `parse()` is one of the few times you'll see
1655 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1656 /// helps the inference algorithm understand specifically which type
1657 /// you're trying to parse into.
1659 /// `parse()` can parse any type that implements the [`FromStr`] trait.
1661 /// [`FromStr`]: str/trait.FromStr.html
1665 /// Will return [`Err`] if it's not possible to parse this string slice into
1666 /// the desired type.
1668 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1675 /// let four: u32 = "4".parse().unwrap();
1677 /// assert_eq!(4, four);
1680 /// Using the 'turbofish' instead of annotating `four`:
1683 /// let four = "4".parse::<u32>();
1685 /// assert_eq!(Ok(4), four);
1688 /// Failing to parse:
1691 /// let nope = "j".parse::<u32>();
1693 /// assert!(nope.is_err());
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1698 core_str::StrExt::parse(self)
1701 /// Replaces all matches of a pattern with another string.
1703 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1704 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1705 /// replaces them with the replacement string slice.
1707 /// [`String`]: string/struct.String.html
1714 /// let s = "this is old";
1716 /// assert_eq!("this is new", s.replace("old", "new"));
1719 /// When the pattern doesn't match:
1722 /// let s = "this is old";
1723 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1725 #[stable(feature = "rust1", since = "1.0.0")]
1726 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1727 let mut result = String::new();
1728 let mut last_end = 0;
1729 for (start, part) in self.match_indices(from) {
1730 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1731 result.push_str(to);
1732 last_end = start + part.len();
1734 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1738 /// Replaces first N matches of a pattern with another string.
1740 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1741 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1742 /// replaces them with the replacement string slice at most `N` times.
1744 /// [`String`]: string/struct.String.html
1751 /// let s = "foo foo 123 foo";
1752 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1753 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1754 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1757 /// When the pattern doesn't match:
1760 /// let s = "this is old";
1761 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1763 #[stable(feature = "str_replacen", since = "1.16.0")]
1764 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1765 // Hope to reduce the times of re-allocation
1766 let mut result = String::with_capacity(32);
1767 let mut last_end = 0;
1768 for (start, part) in self.match_indices(pat).take(count) {
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 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1779 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1782 /// Since some characters can expand into multiple characters when changing
1783 /// the case, this function returns a [`String`] instead of modifying the
1784 /// parameter in-place.
1786 /// [`String`]: string/struct.String.html
1793 /// let s = "HELLO";
1795 /// assert_eq!("hello", s.to_lowercase());
1798 /// A tricky example, with sigma:
1801 /// let sigma = "Σ";
1803 /// assert_eq!("σ", sigma.to_lowercase());
1805 /// // but at the end of a word, it's ς, not σ:
1806 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1808 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1811 /// Languages without case are not changed:
1814 /// let new_year = "农历新年";
1816 /// assert_eq!(new_year, new_year.to_lowercase());
1818 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1819 pub fn to_lowercase(&self) -> String {
1820 let mut s = String::with_capacity(self.len());
1821 for (i, c) in self[..].char_indices() {
1823 // Σ maps to σ, except at the end of a word where it maps to ς.
1824 // This is the only conditional (contextual) but language-independent mapping
1825 // in `SpecialCasing.txt`,
1826 // so hard-code it rather than have a generic "condition" mechanism.
1827 // See https://github.com/rust-lang/rust/issues/26035
1828 map_uppercase_sigma(self, i, &mut s)
1830 s.extend(c.to_lowercase());
1835 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1836 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1837 // for the definition of `Final_Sigma`.
1838 debug_assert!('Σ'.len_utf8() == 2);
1839 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1840 !case_ignoreable_then_cased(from[i + 2..].chars());
1841 to.push_str(if is_word_final { "ς" } else { "σ" });
1844 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1845 use std_unicode::derived_property::{Cased, Case_Ignorable};
1846 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1847 Some(c) => Cased(c),
1853 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1855 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1858 /// Since some characters can expand into multiple characters when changing
1859 /// the case, this function returns a [`String`] instead of modifying the
1860 /// parameter in-place.
1862 /// [`String`]: string/struct.String.html
1869 /// let s = "hello";
1871 /// assert_eq!("HELLO", s.to_uppercase());
1874 /// Scripts without case are not changed:
1877 /// let new_year = "农历新年";
1879 /// assert_eq!(new_year, new_year.to_uppercase());
1881 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1882 pub fn to_uppercase(&self) -> String {
1883 let mut s = String::with_capacity(self.len());
1884 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1888 /// Escapes each char in `s` with `char::escape_debug`.
1889 #[unstable(feature = "str_escape",
1890 reason = "return type may change to be an iterator",
1892 pub fn escape_debug(&self) -> String {
1893 self.chars().flat_map(|c| c.escape_debug()).collect()
1896 /// Escapes each char in `s` with `char::escape_default`.
1897 #[unstable(feature = "str_escape",
1898 reason = "return type may change to be an iterator",
1900 pub fn escape_default(&self) -> String {
1901 self.chars().flat_map(|c| c.escape_default()).collect()
1904 /// Escapes each char in `s` with `char::escape_unicode`.
1905 #[unstable(feature = "str_escape",
1906 reason = "return type may change to be an iterator",
1908 pub fn escape_unicode(&self) -> String {
1909 self.chars().flat_map(|c| c.escape_unicode()).collect()
1912 /// Converts a `Box<str>` into a [`String`] without copying or allocating.
1914 /// [`String`]: string/struct.String.html
1921 /// let string = String::from("birthday gift");
1922 /// let boxed_str = string.clone().into_boxed_str();
1924 /// assert_eq!(boxed_str.into_string(), string);
1926 #[stable(feature = "box_str", since = "1.4.0")]
1927 pub fn into_string(self: Box<str>) -> String {
1929 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1930 String::from_utf8_unchecked(slice.into_vec())
1934 /// Create a [`String`] by repeating a string `n` times.
1936 /// [`String`]: string/struct.String.html
1943 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
1945 #[stable(feature = "repeat_str", since = "1.16.0")]
1946 pub fn repeat(&self, n: usize) -> String {
1947 let mut s = String::with_capacity(self.len() * n);
1948 s.extend((0..n).map(|_| self));