1 // Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Unicode string slices.
13 //! The `&str` type is one of the two main string types, the other being `String`.
14 //! Unlike its `String` counterpart, its contents are borrowed.
18 //! A basic string declaration of `&str` type:
21 //! let hello_world = "Hello, World!";
24 //! Here we have declared a string literal, also known as a string slice.
25 //! String literals have a static lifetime, which means the string `hello_world`
26 //! is guaranteed to be valid for the duration of the entire program.
27 //! We can explicitly specify `hello_world`'s lifetime as well:
30 //! let hello_world: &'static str = "Hello, world!";
33 //! *[See also the `str` primitive type](../../std/primitive.str.html).*
35 #![stable(feature = "rust1", since = "1.0.0")]
37 // Many of the usings in this module are only used in the test configuration.
38 // It's cleaner to just turn off the unused_imports warning than to fix them.
39 #![allow(unused_imports)]
42 use core::str as core_str;
43 use core::str::pattern::Pattern;
44 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
46 use core::iter::FusedIterator;
47 use std_unicode::str::{UnicodeStr, Utf16Encoder};
49 use vec_deque::VecDeque;
50 use borrow::{Borrow, ToOwned};
54 use slice::{SliceConcatExt, SliceIndex};
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub use core::str::{FromStr, Utf8Error};
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub use core::str::{Lines, LinesAny};
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub use core::str::{Split, RSplit};
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub use core::str::{SplitN, RSplitN};
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub use core::str::{SplitTerminator, RSplitTerminator};
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use core::str::{Matches, RMatches};
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub use core::str::{MatchIndices, RMatchIndices};
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub use core::str::{from_utf8, from_utf8_mut, Chars, CharIndices, Bytes};
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError};
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub use std_unicode::str::SplitWhitespace;
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use core::str::pattern;
82 #[unstable(feature = "slice_concat_ext",
83 reason = "trait should not have to exist",
85 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
88 fn concat(&self) -> String {
93 // `len` calculation may overflow but push_str will check boundaries
94 let len = self.iter().map(|s| s.borrow().len()).sum();
95 let mut result = String::with_capacity(len);
98 result.push_str(s.borrow())
104 fn join(&self, sep: &str) -> String {
106 return String::new();
111 return self.concat();
114 // this is wrong without the guarantee that `self` is non-empty
115 // `len` calculation may overflow but push_str but will check boundaries
116 let len = sep.len() * (self.len() - 1) +
117 self.iter().map(|s| s.borrow().len()).sum::<usize>();
118 let mut result = String::with_capacity(len);
119 let mut first = true;
125 result.push_str(sep);
127 result.push_str(s.borrow());
132 fn connect(&self, sep: &str) -> String {
137 /// An iterator of [`u16`] over the string encoded as UTF-16.
139 /// [`u16`]: ../../std/primitive.u16.html
141 /// This struct is created by the [`encode_utf16`] method on [`str`].
142 /// See its documentation for more.
144 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
145 /// [`str`]: ../../std/primitive.str.html
147 #[stable(feature = "encode_utf16", since = "1.8.0")]
148 pub struct EncodeUtf16<'a> {
149 encoder: Utf16Encoder<Chars<'a>>,
152 #[stable(feature = "collection_debug", since = "1.17.0")]
153 impl<'a> fmt::Debug for EncodeUtf16<'a> {
154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
155 f.pad("EncodeUtf16 { .. }")
159 #[stable(feature = "encode_utf16", since = "1.8.0")]
160 impl<'a> Iterator for EncodeUtf16<'a> {
164 fn next(&mut self) -> Option<u16> {
169 fn size_hint(&self) -> (usize, Option<usize>) {
170 self.encoder.size_hint()
174 #[unstable(feature = "fused", issue = "35602")]
175 impl<'a> FusedIterator for EncodeUtf16<'a> {}
177 #[stable(feature = "rust1", since = "1.0.0")]
178 impl Borrow<str> for String {
180 fn borrow(&self) -> &str {
185 #[stable(feature = "rust1", since = "1.0.0")]
186 impl ToOwned for str {
188 fn to_owned(&self) -> String {
189 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
192 fn clone_into(&self, target: &mut String) {
193 let mut b = mem::replace(target, String::new()).into_bytes();
194 self.as_bytes().clone_into(&mut b);
195 *target = unsafe { String::from_utf8_unchecked(b) }
199 /// Methods for string slices.
203 /// Returns the length of `self`.
205 /// This length is in bytes, not [`char`]s or graphemes. In other words,
206 /// it may not be what a human considers the length of the string.
208 /// [`char`]: primitive.char.html
215 /// let len = "foo".len();
216 /// assert_eq!(3, len);
218 /// let len = "ƒoo".len(); // fancy f!
219 /// assert_eq!(4, len);
221 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn len(&self) -> usize {
224 core_str::StrExt::len(self)
227 /// Returns `true` if `self` has a length of zero bytes.
235 /// assert!(s.is_empty());
237 /// let s = "not empty";
238 /// assert!(!s.is_empty());
241 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn is_empty(&self) -> bool {
243 core_str::StrExt::is_empty(self)
246 /// Checks that `index`-th byte lies at the start and/or end of a
247 /// UTF-8 code point sequence.
249 /// The start and end of the string (when `index == self.len()`) are
253 /// Returns `false` if `index` is greater than `self.len()`.
258 /// let s = "Löwe 老虎 Léopard";
259 /// assert!(s.is_char_boundary(0));
261 /// assert!(s.is_char_boundary(6));
262 /// assert!(s.is_char_boundary(s.len()));
264 /// // second byte of `ö`
265 /// assert!(!s.is_char_boundary(2));
267 /// // third byte of `老`
268 /// assert!(!s.is_char_boundary(8));
270 #[stable(feature = "is_char_boundary", since = "1.9.0")]
272 pub fn is_char_boundary(&self, index: usize) -> bool {
273 core_str::StrExt::is_char_boundary(self, index)
276 /// Converts a string slice to a byte slice. To convert the byte slice back
277 /// into a string slice, use the [`str::from_utf8`] function.
279 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
286 /// let bytes = "bors".as_bytes();
287 /// assert_eq!(b"bors", bytes);
289 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn as_bytes(&self) -> &[u8] {
292 core_str::StrExt::as_bytes(self)
295 /// Converts a mutable string slice to a mutable byte slice. To convert the
296 /// mutable byte slice back into a mutable string slice, use the
297 /// [`str::from_utf8_mut`] function.
299 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
306 /// let mut s = String::from("Hello");
307 /// let bytes = unsafe { s.as_bytes_mut() };
309 /// assert_eq!(b"Hello", bytes);
315 /// let mut s = String::from("🗻∈🌏");
318 /// let bytes = s.as_bytes_mut();
326 /// assert_eq!("🍔∈🌏", s);
328 #[stable(feature = "str_mut_extras", since = "1.20.0")]
330 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
331 core_str::StrExt::as_bytes_mut(self)
334 /// Converts a string slice to a raw pointer.
336 /// As string slices are a slice of bytes, the raw pointer points to a
337 /// [`u8`]. This pointer will be pointing to the first byte of the string
340 /// [`u8`]: primitive.u8.html
348 /// let ptr = s.as_ptr();
350 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn as_ptr(&self) -> *const u8 {
353 core_str::StrExt::as_ptr(self)
356 /// Returns a subslice of `str`.
358 /// This is the non-panicking alternative to indexing the `str`. Returns
359 /// [`None`] whenever equivalent indexing operation would panic.
361 /// [`None`]: option/enum.Option.html#variant.None
366 /// let mut v = String::from("🗻∈🌏");
368 /// assert_eq!(Some("🗻"), v.get(0..4));
370 /// // indices not on UTF-8 sequence boundaries
371 /// assert!(v.get_mut(1..).is_none());
372 /// assert!(v.get_mut(..8).is_none());
375 /// assert!(v.get_mut(..42).is_none());
377 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
379 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
380 core_str::StrExt::get(self, i)
383 /// Returns a mutable subslice of `str`.
385 /// This is the non-panicking alternative to indexing the `str`. Returns
386 /// [`None`] whenever equivalent indexing operation would panic.
388 /// [`None`]: option/enum.Option.html#variant.None
393 /// use std::ascii::AsciiExt;
395 /// let mut v = String::from("hello");
396 /// // correct length
397 /// assert!(v.get_mut(0..5).is_some());
399 /// assert!(v.get_mut(..42).is_none());
400 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
402 /// assert_eq!("hello", v);
404 /// let s = v.get_mut(0..2);
405 /// let s = s.map(|s| {
406 /// s.make_ascii_uppercase();
409 /// assert_eq!(Some("HE"), s);
411 /// assert_eq!("HEllo", v);
413 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
415 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
416 core_str::StrExt::get_mut(self, i)
419 /// Returns a unchecked subslice of `str`.
421 /// This is the unchecked alternative to indexing the `str`.
425 /// Callers of this function are responsible that these preconditions are
428 /// * The starting index must come before the ending index;
429 /// * Indexes must be within bounds of the original slice;
430 /// * Indexes must lie on UTF-8 sequence boundaries.
432 /// Failing that, the returned string slice may reference invalid memory or
433 /// violate the invariants communicated by the `str` type.
440 /// assert_eq!("🗻", v.get_unchecked(0..4));
441 /// assert_eq!("∈", v.get_unchecked(4..7));
442 /// assert_eq!("🌏", v.get_unchecked(7..11));
445 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
447 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
448 core_str::StrExt::get_unchecked(self, i)
451 /// Returns a mutable, unchecked subslice of `str`.
453 /// This is the unchecked alternative to indexing the `str`.
457 /// Callers of this function are responsible that these preconditions are
460 /// * The starting index must come before the ending index;
461 /// * Indexes must be within bounds of the original slice;
462 /// * Indexes must lie on UTF-8 sequence boundaries.
464 /// Failing that, the returned string slice may reference invalid memory or
465 /// violate the invariants communicated by the `str` type.
470 /// let mut v = String::from("🗻∈🌏");
472 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
473 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
474 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
477 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
479 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
480 core_str::StrExt::get_unchecked_mut(self, i)
483 /// 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 [`Index`].
489 /// [`str`]: primitive.str.html
490 /// [`Index`]: ops/trait.Index.html
492 /// This new slice goes from `begin` to `end`, including `begin` but
495 /// To get a mutable string slice instead, see the
496 /// [`slice_mut_unchecked`] method.
498 /// [`slice_mut_unchecked`]: #method.slice_mut_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.
514 /// let s = "Löwe 老虎 Léopard";
517 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
520 /// let s = "Hello, world!";
523 /// assert_eq!("world", s.slice_unchecked(7, 12));
526 #[stable(feature = "rust1", since = "1.0.0")]
528 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
529 core_str::StrExt::slice_unchecked(self, begin, end)
532 /// Creates a string slice from another string slice, bypassing safety
534 /// This is generally not recommended, use with caution! For a safe
535 /// alternative see [`str`] and [`IndexMut`].
537 /// [`str`]: primitive.str.html
538 /// [`IndexMut`]: ops/trait.IndexMut.html
540 /// This new slice goes from `begin` to `end`, including `begin` but
543 /// To get an immutable string slice instead, see the
544 /// [`slice_unchecked`] method.
546 /// [`slice_unchecked`]: #method.slice_unchecked
550 /// Callers of this function are responsible that three preconditions are
553 /// * `begin` must come before `end`.
554 /// * `begin` and `end` must be byte positions within the string slice.
555 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
556 #[stable(feature = "str_slice_mut", since = "1.5.0")]
558 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
559 core_str::StrExt::slice_mut_unchecked(self, begin, end)
562 /// Divide one string slice into two at an index.
564 /// The argument, `mid`, should be a byte offset from the start of the
565 /// string. It must also be on the boundary of a UTF-8 code point.
567 /// The two slices returned go from the start of the string slice to `mid`,
568 /// and from `mid` to the end of the string slice.
570 /// To get mutable string slices instead, see the [`split_at_mut`]
573 /// [`split_at_mut`]: #method.split_at_mut
577 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
578 /// beyond the last code point of the string slice.
585 /// let s = "Per Martin-Löf";
587 /// let (first, last) = s.split_at(3);
589 /// assert_eq!("Per", first);
590 /// assert_eq!(" Martin-Löf", last);
593 #[stable(feature = "str_split_at", since = "1.4.0")]
594 pub fn split_at(&self, mid: usize) -> (&str, &str) {
595 core_str::StrExt::split_at(self, mid)
598 /// Divide one mutable string slice into two at an index.
600 /// The argument, `mid`, should be a byte offset from the start of the
601 /// string. It must also be on the boundary of a UTF-8 code point.
603 /// The two slices returned go from the start of the string slice to `mid`,
604 /// and from `mid` to the end of the string slice.
606 /// To get immutable string slices instead, see the [`split_at`] method.
608 /// [`split_at`]: #method.split_at
612 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
613 /// beyond the last code point of the string slice.
620 /// use std::ascii::AsciiExt;
622 /// let mut s = "Per Martin-Löf".to_string();
624 /// let (first, last) = s.split_at_mut(3);
625 /// first.make_ascii_uppercase();
626 /// assert_eq!("PER", first);
627 /// assert_eq!(" Martin-Löf", last);
629 /// assert_eq!("PER Martin-Löf", s);
632 #[stable(feature = "str_split_at", since = "1.4.0")]
633 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
634 core_str::StrExt::split_at_mut(self, mid)
637 /// Returns an iterator over the [`char`]s of a string slice.
639 /// As a string slice consists of valid UTF-8, we can iterate through a
640 /// string slice by [`char`]. This method returns such an iterator.
642 /// It's important to remember that [`char`] represents a Unicode Scalar
643 /// Value, and may not match your idea of what a 'character' is. Iteration
644 /// over grapheme clusters may be what you actually want.
646 /// [`char`]: primitive.char.html
653 /// let word = "goodbye";
655 /// let count = word.chars().count();
656 /// assert_eq!(7, count);
658 /// let mut chars = word.chars();
660 /// assert_eq!(Some('g'), chars.next());
661 /// assert_eq!(Some('o'), chars.next());
662 /// assert_eq!(Some('o'), chars.next());
663 /// assert_eq!(Some('d'), chars.next());
664 /// assert_eq!(Some('b'), chars.next());
665 /// assert_eq!(Some('y'), chars.next());
666 /// assert_eq!(Some('e'), chars.next());
668 /// assert_eq!(None, chars.next());
671 /// Remember, [`char`]s may not match your human intuition about characters:
676 /// let mut chars = y.chars();
678 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
679 /// assert_eq!(Some('\u{0306}'), chars.next());
681 /// assert_eq!(None, chars.next());
683 #[stable(feature = "rust1", since = "1.0.0")]
685 pub fn chars(&self) -> Chars {
686 core_str::StrExt::chars(self)
688 /// Returns an iterator over the [`char`]s of a string slice, and their
691 /// As a string slice consists of valid UTF-8, we can iterate through a
692 /// string slice by [`char`]. This method returns an iterator of both
693 /// these [`char`]s, as well as their byte positions.
695 /// The iterator yields tuples. The position is first, the [`char`] is
698 /// [`char`]: primitive.char.html
705 /// let word = "goodbye";
707 /// let count = word.char_indices().count();
708 /// assert_eq!(7, count);
710 /// let mut char_indices = word.char_indices();
712 /// assert_eq!(Some((0, 'g')), char_indices.next());
713 /// assert_eq!(Some((1, 'o')), char_indices.next());
714 /// assert_eq!(Some((2, 'o')), char_indices.next());
715 /// assert_eq!(Some((3, 'd')), char_indices.next());
716 /// assert_eq!(Some((4, 'b')), char_indices.next());
717 /// assert_eq!(Some((5, 'y')), char_indices.next());
718 /// assert_eq!(Some((6, 'e')), char_indices.next());
720 /// assert_eq!(None, char_indices.next());
723 /// Remember, [`char`]s may not match your human intuition about characters:
728 /// let mut char_indices = y.char_indices();
730 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
731 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
733 /// assert_eq!(None, char_indices.next());
735 #[stable(feature = "rust1", since = "1.0.0")]
737 pub fn char_indices(&self) -> CharIndices {
738 core_str::StrExt::char_indices(self)
741 /// An iterator over the bytes of a string slice.
743 /// As a string slice consists of a sequence of bytes, we can iterate
744 /// through a string slice by byte. This method returns such an iterator.
751 /// let mut bytes = "bors".bytes();
753 /// assert_eq!(Some(b'b'), bytes.next());
754 /// assert_eq!(Some(b'o'), bytes.next());
755 /// assert_eq!(Some(b'r'), bytes.next());
756 /// assert_eq!(Some(b's'), bytes.next());
758 /// assert_eq!(None, bytes.next());
760 #[stable(feature = "rust1", since = "1.0.0")]
762 pub fn bytes(&self) -> Bytes {
763 core_str::StrExt::bytes(self)
766 /// Split a string slice by whitespace.
768 /// The iterator returned will return string slices that are sub-slices of
769 /// the original string slice, separated by any amount of whitespace.
771 /// 'Whitespace' is defined according to the terms of the Unicode Derived
772 /// Core Property `White_Space`.
779 /// let mut iter = "A few words".split_whitespace();
781 /// assert_eq!(Some("A"), iter.next());
782 /// assert_eq!(Some("few"), iter.next());
783 /// assert_eq!(Some("words"), iter.next());
785 /// assert_eq!(None, iter.next());
788 /// All kinds of whitespace are considered:
791 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
792 /// assert_eq!(Some("Mary"), iter.next());
793 /// assert_eq!(Some("had"), iter.next());
794 /// assert_eq!(Some("a"), iter.next());
795 /// assert_eq!(Some("little"), iter.next());
796 /// assert_eq!(Some("lamb"), iter.next());
798 /// assert_eq!(None, iter.next());
800 #[stable(feature = "split_whitespace", since = "1.1.0")]
802 pub fn split_whitespace(&self) -> SplitWhitespace {
803 UnicodeStr::split_whitespace(self)
806 /// An iterator over the lines of a string, as string slices.
808 /// Lines are ended with either a newline (`\n`) or a carriage return with
809 /// a line feed (`\r\n`).
811 /// The final line ending is optional.
818 /// let text = "foo\r\nbar\n\nbaz\n";
819 /// let mut lines = text.lines();
821 /// assert_eq!(Some("foo"), lines.next());
822 /// assert_eq!(Some("bar"), lines.next());
823 /// assert_eq!(Some(""), lines.next());
824 /// assert_eq!(Some("baz"), lines.next());
826 /// assert_eq!(None, lines.next());
829 /// The final line ending isn't required:
832 /// let text = "foo\nbar\n\r\nbaz";
833 /// let mut lines = text.lines();
835 /// assert_eq!(Some("foo"), lines.next());
836 /// assert_eq!(Some("bar"), lines.next());
837 /// assert_eq!(Some(""), lines.next());
838 /// assert_eq!(Some("baz"), lines.next());
840 /// assert_eq!(None, lines.next());
842 #[stable(feature = "rust1", since = "1.0.0")]
844 pub fn lines(&self) -> Lines {
845 core_str::StrExt::lines(self)
848 /// An iterator over the lines of a string.
849 #[stable(feature = "rust1", since = "1.0.0")]
850 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
853 pub fn lines_any(&self) -> LinesAny {
854 core_str::StrExt::lines_any(self)
857 /// Returns an iterator of `u16` over the string encoded as UTF-16.
864 /// let text = "Zażółć gęślą jaźń";
866 /// let utf8_len = text.len();
867 /// let utf16_len = text.encode_utf16().count();
869 /// assert!(utf16_len <= utf8_len);
871 #[stable(feature = "encode_utf16", since = "1.8.0")]
872 pub fn encode_utf16(&self) -> EncodeUtf16 {
873 EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
876 /// Returns `true` if the given pattern matches a sub-slice of
877 /// this string slice.
879 /// Returns `false` if it does not.
886 /// let bananas = "bananas";
888 /// assert!(bananas.contains("nana"));
889 /// assert!(!bananas.contains("apples"));
891 #[stable(feature = "rust1", since = "1.0.0")]
893 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
894 core_str::StrExt::contains(self, pat)
897 /// Returns `true` if the given pattern matches a prefix of this
900 /// Returns `false` if it does not.
907 /// let bananas = "bananas";
909 /// assert!(bananas.starts_with("bana"));
910 /// assert!(!bananas.starts_with("nana"));
912 #[stable(feature = "rust1", since = "1.0.0")]
913 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
914 core_str::StrExt::starts_with(self, pat)
917 /// Returns `true` if the given pattern matches a suffix of this
920 /// Returns `false` if it does not.
927 /// let bananas = "bananas";
929 /// assert!(bananas.ends_with("anas"));
930 /// assert!(!bananas.ends_with("nana"));
932 #[stable(feature = "rust1", since = "1.0.0")]
933 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
934 where P::Searcher: ReverseSearcher<'a>
936 core_str::StrExt::ends_with(self, pat)
939 /// Returns the byte index of the first character of this string slice that
940 /// matches the pattern.
942 /// Returns [`None`] if the pattern doesn't match.
944 /// The pattern can be a `&str`, [`char`], or a closure that determines if
945 /// a character matches.
947 /// [`char`]: primitive.char.html
948 /// [`None`]: option/enum.Option.html#variant.None
955 /// let s = "Löwe 老虎 Léopard";
957 /// assert_eq!(s.find('L'), Some(0));
958 /// assert_eq!(s.find('é'), Some(14));
959 /// assert_eq!(s.find("Léopard"), Some(13));
962 /// More complex patterns with closures:
965 /// let s = "Löwe 老虎 Léopard";
967 /// assert_eq!(s.find(char::is_whitespace), Some(5));
968 /// assert_eq!(s.find(char::is_lowercase), Some(1));
971 /// Not finding the pattern:
974 /// let s = "Löwe 老虎 Léopard";
975 /// let x: &[_] = &['1', '2'];
977 /// assert_eq!(s.find(x), None);
979 #[stable(feature = "rust1", since = "1.0.0")]
981 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
982 core_str::StrExt::find(self, pat)
985 /// Returns the byte index of the last character of this string slice that
986 /// matches the pattern.
988 /// Returns [`None`] if the pattern doesn't match.
990 /// The pattern can be a `&str`, [`char`], or a closure that determines if
991 /// a character matches.
993 /// [`char`]: primitive.char.html
994 /// [`None`]: option/enum.Option.html#variant.None
1001 /// let s = "Löwe 老虎 Léopard";
1003 /// assert_eq!(s.rfind('L'), Some(13));
1004 /// assert_eq!(s.rfind('é'), Some(14));
1007 /// More complex patterns with closures:
1010 /// let s = "Löwe 老虎 Léopard";
1012 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1013 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1016 /// Not finding the pattern:
1019 /// let s = "Löwe 老虎 Léopard";
1020 /// let x: &[_] = &['1', '2'];
1022 /// assert_eq!(s.rfind(x), None);
1024 #[stable(feature = "rust1", since = "1.0.0")]
1026 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1027 where P::Searcher: ReverseSearcher<'a>
1029 core_str::StrExt::rfind(self, pat)
1032 /// An iterator over substrings of this string slice, separated by
1033 /// characters matched by a pattern.
1035 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1038 /// # Iterator behavior
1040 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1041 /// allows a reverse search and forward/reverse search yields the same
1042 /// elements. This is true for, eg, [`char`] but not for `&str`.
1044 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1046 /// If the pattern allows a reverse search but its results might differ
1047 /// from a forward search, the [`rsplit`] method can be used.
1049 /// [`char`]: primitive.char.html
1050 /// [`rsplit`]: #method.rsplit
1054 /// Simple patterns:
1057 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1058 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1060 /// let v: Vec<&str> = "".split('X').collect();
1061 /// assert_eq!(v, [""]);
1063 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1064 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1066 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1067 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1069 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1070 /// assert_eq!(v, ["abc", "def", "ghi"]);
1072 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1073 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1076 /// A more complex pattern, using a closure:
1079 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1080 /// assert_eq!(v, ["abc", "def", "ghi"]);
1083 /// If a string contains multiple contiguous separators, you will end up
1084 /// with empty strings in the output:
1087 /// let x = "||||a||b|c".to_string();
1088 /// let d: Vec<_> = x.split('|').collect();
1090 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1093 /// Contiguous separators are separated by the empty string.
1096 /// let x = "(///)".to_string();
1097 /// let d: Vec<_> = x.split('/').collect();
1099 /// assert_eq!(d, &["(", "", "", ")"]);
1102 /// Separators at the start or end of a string are neighbored
1103 /// by empty strings.
1106 /// let d: Vec<_> = "010".split("0").collect();
1107 /// assert_eq!(d, &["", "1", ""]);
1110 /// When the empty string is used as a separator, it separates
1111 /// every character in the string, along with the beginning
1112 /// and end of the string.
1115 /// let f: Vec<_> = "rust".split("").collect();
1116 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1119 /// Contiguous separators can lead to possibly surprising behavior
1120 /// when whitespace is used as the separator. This code is correct:
1123 /// let x = " a b c".to_string();
1124 /// let d: Vec<_> = x.split(' ').collect();
1126 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1129 /// It does _not_ give you:
1132 /// assert_eq!(d, &["a", "b", "c"]);
1135 /// Use [`split_whitespace`] for this behavior.
1137 /// [`split_whitespace`]: #method.split_whitespace
1138 #[stable(feature = "rust1", since = "1.0.0")]
1140 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1141 core_str::StrExt::split(self, pat)
1144 /// An iterator over substrings of the given string slice, separated by
1145 /// characters matched by a pattern and yielded in reverse order.
1147 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1150 /// [`char`]: primitive.char.html
1152 /// # Iterator behavior
1154 /// The returned iterator requires that the pattern supports a reverse
1155 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1156 /// search yields the same elements.
1158 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1160 /// For iterating from the front, the [`split`] method can be used.
1162 /// [`split`]: #method.split
1166 /// Simple patterns:
1169 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1170 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1172 /// let v: Vec<&str> = "".rsplit('X').collect();
1173 /// assert_eq!(v, [""]);
1175 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1176 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1178 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1179 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1182 /// A more complex pattern, using a closure:
1185 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1186 /// assert_eq!(v, ["ghi", "def", "abc"]);
1188 #[stable(feature = "rust1", since = "1.0.0")]
1190 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1191 where P::Searcher: ReverseSearcher<'a>
1193 core_str::StrExt::rsplit(self, pat)
1196 /// An iterator over substrings of the given string slice, separated by
1197 /// characters matched by a pattern.
1199 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1202 /// Equivalent to [`split`], except that the trailing substring
1203 /// is skipped if empty.
1205 /// [`split`]: #method.split
1207 /// This method can be used for string data that is _terminated_,
1208 /// rather than _separated_ by a pattern.
1210 /// # Iterator behavior
1212 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1213 /// allows a reverse search and forward/reverse search yields the same
1214 /// elements. This is true for, eg, [`char`] but not for `&str`.
1216 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1217 /// [`char`]: primitive.char.html
1219 /// If the pattern allows a reverse search but its results might differ
1220 /// from a forward search, the [`rsplit_terminator`] method can be used.
1222 /// [`rsplit_terminator`]: #method.rsplit_terminator
1229 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1230 /// assert_eq!(v, ["A", "B"]);
1232 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1233 /// assert_eq!(v, ["A", "", "B", ""]);
1235 #[stable(feature = "rust1", since = "1.0.0")]
1237 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1238 core_str::StrExt::split_terminator(self, pat)
1241 /// An iterator over substrings of `self`, separated by characters
1242 /// matched by a pattern and yielded in reverse order.
1244 /// The pattern can be a simple `&str`, [`char`], or a closure that
1245 /// determines the split.
1246 /// Additional libraries might provide more complex patterns like
1247 /// regular expressions.
1249 /// [`char`]: primitive.char.html
1251 /// Equivalent to [`split`], except that the trailing substring is
1252 /// skipped if empty.
1254 /// [`split`]: #method.split
1256 /// This method can be used for string data that is _terminated_,
1257 /// rather than _separated_ by a pattern.
1259 /// # Iterator behavior
1261 /// The returned iterator requires that the pattern supports a
1262 /// reverse search, and it will be double ended if a forward/reverse
1263 /// search yields the same elements.
1265 /// For iterating from the front, the [`split_terminator`] method can be
1268 /// [`split_terminator`]: #method.split_terminator
1273 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1274 /// assert_eq!(v, ["B", "A"]);
1276 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1277 /// assert_eq!(v, ["", "B", "", "A"]);
1279 #[stable(feature = "rust1", since = "1.0.0")]
1281 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1282 where P::Searcher: ReverseSearcher<'a>
1284 core_str::StrExt::rsplit_terminator(self, pat)
1287 /// An iterator over substrings of the given string slice, separated by a
1288 /// pattern, restricted to returning at most `n` items.
1290 /// If `n` substrings are returned, the last substring (the `n`th substring)
1291 /// will contain the remainder of the string.
1293 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1296 /// [`char`]: primitive.char.html
1298 /// # Iterator behavior
1300 /// The returned iterator will not be double ended, because it is
1301 /// not efficient to support.
1303 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1306 /// [`rsplitn`]: #method.rsplitn
1310 /// Simple patterns:
1313 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1314 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1316 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1317 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1319 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1320 /// assert_eq!(v, ["abcXdef"]);
1322 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1323 /// assert_eq!(v, [""]);
1326 /// A more complex pattern, using a closure:
1329 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1330 /// assert_eq!(v, ["abc", "defXghi"]);
1332 #[stable(feature = "rust1", since = "1.0.0")]
1334 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1335 core_str::StrExt::splitn(self, n, pat)
1338 /// An iterator over substrings of this string slice, separated by a
1339 /// pattern, starting from the end of the string, restricted to returning
1340 /// at most `n` items.
1342 /// If `n` substrings are returned, the last substring (the `n`th substring)
1343 /// will contain the remainder of the string.
1345 /// The pattern can be a `&str`, [`char`], or a closure that
1346 /// determines the split.
1348 /// [`char`]: primitive.char.html
1350 /// # Iterator behavior
1352 /// The returned iterator will not be double ended, because it is not
1353 /// efficient to support.
1355 /// For splitting from the front, the [`splitn`] method can be used.
1357 /// [`splitn`]: #method.splitn
1361 /// Simple patterns:
1364 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1365 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1367 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1368 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1370 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1371 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1374 /// A more complex pattern, using a closure:
1377 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1378 /// assert_eq!(v, ["ghi", "abc1def"]);
1380 #[stable(feature = "rust1", since = "1.0.0")]
1382 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1383 where P::Searcher: ReverseSearcher<'a>
1385 core_str::StrExt::rsplitn(self, n, pat)
1388 /// An iterator over the disjoint matches of a pattern within the given string
1391 /// The pattern can be a `&str`, [`char`], or a closure that
1392 /// determines if a character matches.
1394 /// [`char`]: primitive.char.html
1396 /// # Iterator behavior
1398 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1399 /// allows a reverse search and forward/reverse search yields the same
1400 /// elements. This is true for, eg, [`char`] but not for `&str`.
1402 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1403 /// [`char`]: primitive.char.html
1405 /// If the pattern allows a reverse search but its results might differ
1406 /// from a forward search, the [`rmatches`] method can be used.
1408 /// [`rmatches`]: #method.rmatches
1415 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1416 /// assert_eq!(v, ["abc", "abc", "abc"]);
1418 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1419 /// assert_eq!(v, ["1", "2", "3"]);
1421 #[stable(feature = "str_matches", since = "1.2.0")]
1423 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1424 core_str::StrExt::matches(self, pat)
1427 /// An iterator over the disjoint matches of a pattern within this string slice,
1428 /// yielded in reverse order.
1430 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1431 /// a character matches.
1433 /// [`char`]: primitive.char.html
1435 /// # Iterator behavior
1437 /// The returned iterator requires that the pattern supports a reverse
1438 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1439 /// search yields the same elements.
1441 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1443 /// For iterating from the front, the [`matches`] method can be used.
1445 /// [`matches`]: #method.matches
1452 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1453 /// assert_eq!(v, ["abc", "abc", "abc"]);
1455 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1456 /// assert_eq!(v, ["3", "2", "1"]);
1458 #[stable(feature = "str_matches", since = "1.2.0")]
1460 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1461 where P::Searcher: ReverseSearcher<'a>
1463 core_str::StrExt::rmatches(self, pat)
1466 /// An iterator over the disjoint matches of a pattern within this string
1467 /// slice as well as the index that the match starts at.
1469 /// For matches of `pat` within `self` that overlap, only the indices
1470 /// corresponding to the first match are returned.
1472 /// The pattern can be a `&str`, [`char`], or a closure that determines
1473 /// if a character matches.
1475 /// [`char`]: primitive.char.html
1477 /// # Iterator behavior
1479 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1480 /// allows a reverse search and forward/reverse search yields the same
1481 /// elements. This is true for, eg, [`char`] but not for `&str`.
1483 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1485 /// If the pattern allows a reverse search but its results might differ
1486 /// from a forward search, the [`rmatch_indices`] method can be used.
1488 /// [`rmatch_indices`]: #method.rmatch_indices
1495 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1496 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1498 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1499 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1501 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1502 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1504 #[stable(feature = "str_match_indices", since = "1.5.0")]
1506 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1507 core_str::StrExt::match_indices(self, pat)
1510 /// An iterator over the disjoint matches of a pattern within `self`,
1511 /// yielded in reverse order along with the index of the match.
1513 /// For matches of `pat` within `self` that overlap, only the indices
1514 /// corresponding to the last match are returned.
1516 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1517 /// character matches.
1519 /// [`char`]: primitive.char.html
1521 /// # Iterator behavior
1523 /// The returned iterator requires that the pattern supports a reverse
1524 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1525 /// search yields the same elements.
1527 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1529 /// For iterating from the front, the [`match_indices`] method can be used.
1531 /// [`match_indices`]: #method.match_indices
1538 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1539 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1541 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1542 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1544 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1545 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1547 #[stable(feature = "str_match_indices", since = "1.5.0")]
1549 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1550 where P::Searcher: ReverseSearcher<'a>
1552 core_str::StrExt::rmatch_indices(self, pat)
1555 /// Returns a string slice with leading and trailing whitespace removed.
1557 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1558 /// Core Property `White_Space`.
1565 /// let s = " Hello\tworld\t";
1567 /// assert_eq!("Hello\tworld", s.trim());
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 pub fn trim(&self) -> &str {
1571 UnicodeStr::trim(self)
1574 /// Returns a string slice with leading whitespace removed.
1576 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1577 /// Core Property `White_Space`.
1579 /// # Text directionality
1581 /// A string is a sequence of bytes. 'Left' in this context means the first
1582 /// position of that byte string; for a language like Arabic or Hebrew
1583 /// which are 'right to left' rather than 'left to right', this will be
1584 /// the _right_ side, not the left.
1591 /// let s = " Hello\tworld\t";
1593 /// assert_eq!("Hello\tworld\t", s.trim_left());
1599 /// let s = " English";
1600 /// assert!(Some('E') == s.trim_left().chars().next());
1602 /// let s = " עברית";
1603 /// assert!(Some('ע') == s.trim_left().chars().next());
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 pub fn trim_left(&self) -> &str {
1607 UnicodeStr::trim_left(self)
1610 /// Returns a string slice with trailing whitespace removed.
1612 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1613 /// Core Property `White_Space`.
1615 /// # Text directionality
1617 /// A string is a sequence of bytes. 'Right' in this context means the last
1618 /// position of that byte string; for a language like Arabic or Hebrew
1619 /// which are 'right to left' rather than 'left to right', this will be
1620 /// the _left_ side, not the right.
1627 /// let s = " Hello\tworld\t";
1629 /// assert_eq!(" Hello\tworld", s.trim_right());
1635 /// let s = "English ";
1636 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1638 /// let s = "עברית ";
1639 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 pub fn trim_right(&self) -> &str {
1643 UnicodeStr::trim_right(self)
1646 /// Returns a string slice with all prefixes and suffixes that match a
1647 /// pattern repeatedly removed.
1649 /// The pattern can be a [`char`] or a closure that determines if a
1650 /// character matches.
1652 /// [`char`]: primitive.char.html
1656 /// Simple patterns:
1659 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1660 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1662 /// let x: &[_] = &['1', '2'];
1663 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1666 /// A more complex pattern, using a closure:
1669 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1673 where P::Searcher: DoubleEndedSearcher<'a>
1675 core_str::StrExt::trim_matches(self, pat)
1678 /// Returns a string slice with all prefixes that match a pattern
1679 /// repeatedly removed.
1681 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1682 /// a character matches.
1684 /// [`char`]: primitive.char.html
1686 /// # Text directionality
1688 /// A string is a sequence of bytes. 'Left' in this context means the first
1689 /// position of that byte string; for a language like Arabic or Hebrew
1690 /// which are 'right to left' rather than 'left to right', this will be
1691 /// the _right_ side, not the left.
1698 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1699 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1701 /// let x: &[_] = &['1', '2'];
1702 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1706 core_str::StrExt::trim_left_matches(self, pat)
1709 /// Returns a string slice with all suffixes that match a pattern
1710 /// repeatedly removed.
1712 /// The pattern can be a `&str`, [`char`], or a closure that
1713 /// determines if a character matches.
1715 /// [`char`]: primitive.char.html
1717 /// # Text directionality
1719 /// A string is a sequence of bytes. 'Right' in this context means the last
1720 /// position of that byte string; for a language like Arabic or Hebrew
1721 /// which are 'right to left' rather than 'left to right', this will be
1722 /// the _left_ side, not the right.
1726 /// Simple patterns:
1729 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1730 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1732 /// let x: &[_] = &['1', '2'];
1733 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1736 /// A more complex pattern, using a closure:
1739 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1741 #[stable(feature = "rust1", since = "1.0.0")]
1742 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1743 where P::Searcher: ReverseSearcher<'a>
1745 core_str::StrExt::trim_right_matches(self, pat)
1748 /// Parses this string slice into another type.
1750 /// Because `parse` is so general, it can cause problems with type
1751 /// inference. As such, `parse` is one of the few times you'll see
1752 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1753 /// helps the inference algorithm understand specifically which type
1754 /// you're trying to parse into.
1756 /// `parse` can parse any type that implements the [`FromStr`] trait.
1758 /// [`FromStr`]: str/trait.FromStr.html
1762 /// Will return [`Err`] if it's not possible to parse this string slice into
1763 /// the desired type.
1765 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1772 /// let four: u32 = "4".parse().unwrap();
1774 /// assert_eq!(4, four);
1777 /// Using the 'turbofish' instead of annotating `four`:
1780 /// let four = "4".parse::<u32>();
1782 /// assert_eq!(Ok(4), four);
1785 /// Failing to parse:
1788 /// let nope = "j".parse::<u32>();
1790 /// assert!(nope.is_err());
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1795 core_str::StrExt::parse(self)
1798 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
1805 /// let s = "this is a string";
1806 /// let boxed_str = s.to_owned().into_boxed_str();
1807 /// let boxed_bytes = boxed_str.into_boxed_bytes();
1808 /// assert_eq!(*boxed_bytes, *s.as_bytes());
1810 #[stable(feature = "str_box_extras", since = "1.20.0")]
1811 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
1815 /// Replaces all matches of a pattern with another string.
1817 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1818 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1819 /// replaces them with the replacement string slice.
1821 /// [`String`]: string/struct.String.html
1828 /// let s = "this is old";
1830 /// assert_eq!("this is new", s.replace("old", "new"));
1833 /// When the pattern doesn't match:
1836 /// let s = "this is old";
1837 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1839 #[stable(feature = "rust1", since = "1.0.0")]
1841 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1842 let mut result = String::new();
1843 let mut last_end = 0;
1844 for (start, part) in self.match_indices(from) {
1845 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1846 result.push_str(to);
1847 last_end = start + part.len();
1849 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1853 /// Replaces first N matches of a pattern with another string.
1855 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1856 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1857 /// replaces them with the replacement string slice at most `count` times.
1859 /// [`String`]: string/struct.String.html
1866 /// let s = "foo foo 123 foo";
1867 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1868 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1869 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1872 /// When the pattern doesn't match:
1875 /// let s = "this is old";
1876 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1878 #[stable(feature = "str_replacen", since = "1.16.0")]
1879 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1880 // Hope to reduce the times of re-allocation
1881 let mut result = String::with_capacity(32);
1882 let mut last_end = 0;
1883 for (start, part) in self.match_indices(pat).take(count) {
1884 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1885 result.push_str(to);
1886 last_end = start + part.len();
1888 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1892 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1894 /// 'Lowercase' 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_lowercase());
1913 /// A tricky example, with sigma:
1916 /// let sigma = "Σ";
1918 /// assert_eq!("σ", sigma.to_lowercase());
1920 /// // but at the end of a word, it's ς, not σ:
1921 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1923 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1926 /// Languages without case are not changed:
1929 /// let new_year = "农历新年";
1931 /// assert_eq!(new_year, new_year.to_lowercase());
1933 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1934 pub fn to_lowercase(&self) -> String {
1935 let mut s = String::with_capacity(self.len());
1936 for (i, c) in self[..].char_indices() {
1938 // Σ maps to σ, except at the end of a word where it maps to ς.
1939 // This is the only conditional (contextual) but language-independent mapping
1940 // in `SpecialCasing.txt`,
1941 // so hard-code it rather than have a generic "condition" mechanism.
1942 // See https://github.com/rust-lang/rust/issues/26035
1943 map_uppercase_sigma(self, i, &mut s)
1945 s.extend(c.to_lowercase());
1950 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1951 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1952 // for the definition of `Final_Sigma`.
1953 debug_assert!('Σ'.len_utf8() == 2);
1954 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1955 !case_ignoreable_then_cased(from[i + 2..].chars());
1956 to.push_str(if is_word_final { "ς" } else { "σ" });
1959 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1960 use std_unicode::derived_property::{Cased, Case_Ignorable};
1961 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1962 Some(c) => Cased(c),
1968 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1970 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1973 /// Since some characters can expand into multiple characters when changing
1974 /// the case, this function returns a [`String`] instead of modifying the
1975 /// parameter in-place.
1977 /// [`String`]: string/struct.String.html
1984 /// let s = "hello";
1986 /// assert_eq!("HELLO", s.to_uppercase());
1989 /// Scripts without case are not changed:
1992 /// let new_year = "农历新年";
1994 /// assert_eq!(new_year, new_year.to_uppercase());
1996 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1997 pub fn to_uppercase(&self) -> String {
1998 let mut s = String::with_capacity(self.len());
1999 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
2003 /// Escapes each char in `s` with [`char::escape_debug`].
2005 /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
2006 #[unstable(feature = "str_escape",
2007 reason = "return type may change to be an iterator",
2009 pub fn escape_debug(&self) -> String {
2010 self.chars().flat_map(|c| c.escape_debug()).collect()
2013 /// Escapes each char in `s` with [`char::escape_default`].
2015 /// [`char::escape_default`]: primitive.char.html#method.escape_default
2016 #[unstable(feature = "str_escape",
2017 reason = "return type may change to be an iterator",
2019 pub fn escape_default(&self) -> String {
2020 self.chars().flat_map(|c| c.escape_default()).collect()
2023 /// Escapes each char in `s` with [`char::escape_unicode`].
2025 /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
2026 #[unstable(feature = "str_escape",
2027 reason = "return type may change to be an iterator",
2029 pub fn escape_unicode(&self) -> String {
2030 self.chars().flat_map(|c| c.escape_unicode()).collect()
2033 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
2035 /// [`String`]: string/struct.String.html
2036 /// [`Box<str>`]: boxed/struct.Box.html
2043 /// let string = String::from("birthday gift");
2044 /// let boxed_str = string.clone().into_boxed_str();
2046 /// assert_eq!(boxed_str.into_string(), string);
2048 #[stable(feature = "box_str", since = "1.4.0")]
2049 pub fn into_string(self: Box<str>) -> String {
2050 let slice = Box::<[u8]>::from(self);
2051 unsafe { String::from_utf8_unchecked(slice.into_vec()) }
2054 /// Create a [`String`] by repeating a string `n` times.
2056 /// [`String`]: string/struct.String.html
2063 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
2065 #[stable(feature = "repeat_str", since = "1.16.0")]
2066 pub fn repeat(&self, n: usize) -> String {
2067 let mut s = String::with_capacity(self.len() * n);
2068 s.extend((0..n).map(|_| self));
2073 /// Converts a boxed slice of bytes to a boxed string slice without checking
2074 /// that the string contains valid UTF-8.
2081 /// let smile_utf8 = Box::new([226, 152, 186]);
2082 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
2084 /// assert_eq!("☺", &*smile);
2086 #[stable(feature = "str_box_extras", since = "1.20.0")]
2087 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
2088 Box::from_raw(Box::into_raw(v) as *mut str)