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};
47 use core::iter::FusedIterator;
48 use std_unicode::str::{UnicodeStr, Utf16Encoder};
50 use vec_deque::VecDeque;
51 use borrow::{Borrow, ToOwned};
55 use slice::{SliceConcatExt, SliceIndex};
58 #[stable(feature = "rust1", since = "1.0.0")]
59 pub use core::str::{FromStr, Utf8Error};
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub use core::str::{Lines, LinesAny};
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub use core::str::{Split, RSplit};
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub use core::str::{SplitN, RSplitN};
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub use core::str::{SplitTerminator, RSplitTerminator};
69 #[stable(feature = "rust1", since = "1.0.0")]
70 pub use core::str::{Matches, RMatches};
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub use core::str::{MatchIndices, RMatchIndices};
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub use core::str::{from_utf8, from_utf8_mut, Chars, CharIndices, Bytes};
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError};
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub use std_unicode::str::SplitWhitespace;
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub use core::str::pattern;
83 #[unstable(feature = "slice_concat_ext",
84 reason = "trait should not have to exist",
86 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
89 fn concat(&self) -> String {
94 // `len` calculation may overflow but push_str will check boundaries
95 let len = self.iter().map(|s| s.borrow().len()).sum();
96 let mut result = String::with_capacity(len);
99 result.push_str(s.borrow())
105 fn join(&self, sep: &str) -> String {
107 return String::new();
112 return self.concat();
115 // this is wrong without the guarantee that `self` is non-empty
116 // `len` calculation may overflow but push_str but will check boundaries
117 let len = sep.len() * (self.len() - 1) +
118 self.iter().map(|s| s.borrow().len()).sum::<usize>();
119 let mut result = String::with_capacity(len);
120 let mut first = true;
126 result.push_str(sep);
128 result.push_str(s.borrow());
133 fn connect(&self, sep: &str) -> String {
138 /// An iterator of [`u16`] over the string encoded as UTF-16.
140 /// [`u16`]: ../../std/primitive.u16.html
142 /// This struct is created by the [`encode_utf16`] method on [`str`].
143 /// See its documentation for more.
145 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
146 /// [`str`]: ../../std/primitive.str.html
148 #[stable(feature = "encode_utf16", since = "1.8.0")]
149 pub struct EncodeUtf16<'a> {
150 encoder: Utf16Encoder<Chars<'a>>,
153 #[stable(feature = "collection_debug", since = "1.17.0")]
154 impl<'a> fmt::Debug for EncodeUtf16<'a> {
155 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
156 f.pad("EncodeUtf16 { .. }")
160 #[stable(feature = "encode_utf16", since = "1.8.0")]
161 impl<'a> Iterator for EncodeUtf16<'a> {
165 fn next(&mut self) -> Option<u16> {
170 fn size_hint(&self) -> (usize, Option<usize>) {
171 self.encoder.size_hint()
175 #[stable(feature = "fused", since = "1.26.0")]
176 impl<'a> FusedIterator for EncodeUtf16<'a> {}
178 #[stable(feature = "rust1", since = "1.0.0")]
179 impl Borrow<str> for String {
181 fn borrow(&self) -> &str {
186 #[stable(feature = "rust1", since = "1.0.0")]
187 impl ToOwned for str {
189 fn to_owned(&self) -> String {
190 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
193 fn clone_into(&self, target: &mut String) {
194 let mut b = mem::replace(target, String::new()).into_bytes();
195 self.as_bytes().clone_into(&mut b);
196 *target = unsafe { String::from_utf8_unchecked(b) }
200 /// Methods for string slices.
204 /// Returns the length of `self`.
206 /// This length is in bytes, not [`char`]s or graphemes. In other words,
207 /// it may not be what a human considers the length of the string.
209 /// [`char`]: primitive.char.html
216 /// let len = "foo".len();
217 /// assert_eq!(3, len);
219 /// let len = "ƒoo".len(); // fancy f!
220 /// assert_eq!(4, len);
222 #[stable(feature = "rust1", since = "1.0.0")]
224 pub fn len(&self) -> usize {
225 core_str::StrExt::len(self)
228 /// Returns `true` if `self` has a length of zero bytes.
236 /// assert!(s.is_empty());
238 /// let s = "not empty";
239 /// assert!(!s.is_empty());
242 #[stable(feature = "rust1", since = "1.0.0")]
243 pub fn is_empty(&self) -> bool {
244 core_str::StrExt::is_empty(self)
247 /// Checks that `index`-th byte lies at the start and/or end of a
248 /// UTF-8 code point sequence.
250 /// The start and end of the string (when `index == self.len()`) are
254 /// Returns `false` if `index` is greater than `self.len()`.
259 /// let s = "Löwe 老虎 Léopard";
260 /// assert!(s.is_char_boundary(0));
262 /// assert!(s.is_char_boundary(6));
263 /// assert!(s.is_char_boundary(s.len()));
265 /// // second byte of `ö`
266 /// assert!(!s.is_char_boundary(2));
268 /// // third byte of `老`
269 /// assert!(!s.is_char_boundary(8));
271 #[stable(feature = "is_char_boundary", since = "1.9.0")]
273 pub fn is_char_boundary(&self, index: usize) -> bool {
274 core_str::StrExt::is_char_boundary(self, index)
277 /// Converts a string slice to a byte slice. To convert the byte slice back
278 /// into a string slice, use the [`str::from_utf8`] function.
280 /// [`str::from_utf8`]: ./str/fn.from_utf8.html
287 /// let bytes = "bors".as_bytes();
288 /// assert_eq!(b"bors", bytes);
290 #[stable(feature = "rust1", since = "1.0.0")]
292 pub fn as_bytes(&self) -> &[u8] {
293 core_str::StrExt::as_bytes(self)
296 /// Converts a mutable string slice to a mutable byte slice. To convert the
297 /// mutable byte slice back into a mutable string slice, use the
298 /// [`str::from_utf8_mut`] function.
300 /// [`str::from_utf8_mut`]: ./str/fn.from_utf8_mut.html
307 /// let mut s = String::from("Hello");
308 /// let bytes = unsafe { s.as_bytes_mut() };
310 /// assert_eq!(b"Hello", bytes);
316 /// let mut s = String::from("🗻∈🌏");
319 /// let bytes = s.as_bytes_mut();
327 /// assert_eq!("🍔∈🌏", s);
329 #[stable(feature = "str_mut_extras", since = "1.20.0")]
331 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
332 core_str::StrExt::as_bytes_mut(self)
335 /// Converts a string slice to a raw pointer.
337 /// As string slices are a slice of bytes, the raw pointer points to a
338 /// [`u8`]. This pointer will be pointing to the first byte of the string
341 /// [`u8`]: primitive.u8.html
349 /// let ptr = s.as_ptr();
351 #[stable(feature = "rust1", since = "1.0.0")]
353 pub fn as_ptr(&self) -> *const u8 {
354 core_str::StrExt::as_ptr(self)
357 /// Returns a subslice of `str`.
359 /// This is the non-panicking alternative to indexing the `str`. Returns
360 /// [`None`] whenever equivalent indexing operation would panic.
362 /// [`None`]: option/enum.Option.html#variant.None
367 /// let v = String::from("🗻∈🌏");
369 /// assert_eq!(Some("🗻"), v.get(0..4));
371 /// // indices not on UTF-8 sequence boundaries
372 /// assert!(v.get(1..).is_none());
373 /// assert!(v.get(..8).is_none());
376 /// assert!(v.get(..42).is_none());
378 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
380 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
381 core_str::StrExt::get(self, i)
384 /// Returns a mutable subslice of `str`.
386 /// This is the non-panicking alternative to indexing the `str`. Returns
387 /// [`None`] whenever equivalent indexing operation would panic.
389 /// [`None`]: option/enum.Option.html#variant.None
394 /// let mut v = String::from("hello");
395 /// // correct length
396 /// assert!(v.get_mut(0..5).is_some());
398 /// assert!(v.get_mut(..42).is_none());
399 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
401 /// assert_eq!("hello", v);
403 /// let s = v.get_mut(0..2);
404 /// let s = s.map(|s| {
405 /// s.make_ascii_uppercase();
408 /// assert_eq!(Some("HE"), s);
410 /// assert_eq!("HEllo", v);
412 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
414 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
415 core_str::StrExt::get_mut(self, i)
418 /// Returns a unchecked subslice of `str`.
420 /// This is the unchecked alternative to indexing the `str`.
424 /// Callers of this function are responsible that these preconditions are
427 /// * The starting index must come before the ending index;
428 /// * Indexes must be within bounds of the original slice;
429 /// * Indexes must lie on UTF-8 sequence boundaries.
431 /// Failing that, the returned string slice may reference invalid memory or
432 /// violate the invariants communicated by the `str` type.
439 /// assert_eq!("🗻", v.get_unchecked(0..4));
440 /// assert_eq!("∈", v.get_unchecked(4..7));
441 /// assert_eq!("🌏", v.get_unchecked(7..11));
444 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
446 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
447 core_str::StrExt::get_unchecked(self, i)
450 /// Returns a mutable, unchecked subslice of `str`.
452 /// This is the unchecked alternative to indexing the `str`.
456 /// Callers of this function are responsible that these preconditions are
459 /// * The starting index must come before the ending index;
460 /// * Indexes must be within bounds of the original slice;
461 /// * Indexes must lie on UTF-8 sequence boundaries.
463 /// Failing that, the returned string slice may reference invalid memory or
464 /// violate the invariants communicated by the `str` type.
469 /// let mut v = String::from("🗻∈🌏");
471 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
472 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
473 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
476 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
478 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
479 core_str::StrExt::get_unchecked_mut(self, i)
482 /// Creates a string slice from another string slice, bypassing safety
485 /// This is generally not recommended, use with caution! For a safe
486 /// alternative see [`str`] and [`Index`].
488 /// [`str`]: primitive.str.html
489 /// [`Index`]: ops/trait.Index.html
491 /// This new slice goes from `begin` to `end`, including `begin` but
494 /// To get a mutable string slice instead, see the
495 /// [`slice_mut_unchecked`] method.
497 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
501 /// Callers of this function are responsible that three preconditions are
504 /// * `begin` must come before `end`.
505 /// * `begin` and `end` must be byte positions within the string slice.
506 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
513 /// let s = "Löwe 老虎 Léopard";
516 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
519 /// let s = "Hello, world!";
522 /// assert_eq!("world", s.slice_unchecked(7, 12));
525 #[stable(feature = "rust1", since = "1.0.0")]
527 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
528 core_str::StrExt::slice_unchecked(self, begin, end)
531 /// Creates a string slice from another string slice, bypassing safety
533 /// This is generally not recommended, use with caution! For a safe
534 /// alternative see [`str`] and [`IndexMut`].
536 /// [`str`]: primitive.str.html
537 /// [`IndexMut`]: ops/trait.IndexMut.html
539 /// This new slice goes from `begin` to `end`, including `begin` but
542 /// To get an immutable string slice instead, see the
543 /// [`slice_unchecked`] method.
545 /// [`slice_unchecked`]: #method.slice_unchecked
549 /// Callers of this function are responsible that three preconditions are
552 /// * `begin` must come before `end`.
553 /// * `begin` and `end` must be byte positions within the string slice.
554 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
555 #[stable(feature = "str_slice_mut", since = "1.5.0")]
557 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
558 core_str::StrExt::slice_mut_unchecked(self, begin, end)
561 /// Divide one string slice into two at an index.
563 /// The argument, `mid`, should be a byte offset from the start of the
564 /// string. It must also be on the boundary of a UTF-8 code point.
566 /// The two slices returned go from the start of the string slice to `mid`,
567 /// and from `mid` to the end of the string slice.
569 /// To get mutable string slices instead, see the [`split_at_mut`]
572 /// [`split_at_mut`]: #method.split_at_mut
576 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
577 /// beyond the last code point of the string slice.
584 /// let s = "Per Martin-Löf";
586 /// let (first, last) = s.split_at(3);
588 /// assert_eq!("Per", first);
589 /// assert_eq!(" Martin-Löf", last);
592 #[stable(feature = "str_split_at", since = "1.4.0")]
593 pub fn split_at(&self, mid: usize) -> (&str, &str) {
594 core_str::StrExt::split_at(self, mid)
597 /// Divide one mutable string slice into two at an index.
599 /// The argument, `mid`, should be a byte offset from the start of the
600 /// string. It must also be on the boundary of a UTF-8 code point.
602 /// The two slices returned go from the start of the string slice to `mid`,
603 /// and from `mid` to the end of the string slice.
605 /// To get immutable string slices instead, see the [`split_at`] method.
607 /// [`split_at`]: #method.split_at
611 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
612 /// beyond the last code point of the string slice.
619 /// let mut s = "Per Martin-Löf".to_string();
621 /// let (first, last) = s.split_at_mut(3);
622 /// first.make_ascii_uppercase();
623 /// assert_eq!("PER", first);
624 /// assert_eq!(" Martin-Löf", last);
626 /// assert_eq!("PER Martin-Löf", s);
629 #[stable(feature = "str_split_at", since = "1.4.0")]
630 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
631 core_str::StrExt::split_at_mut(self, mid)
634 /// Returns an iterator over the [`char`]s of a string slice.
636 /// As a string slice consists of valid UTF-8, we can iterate through a
637 /// string slice by [`char`]. This method returns such an iterator.
639 /// It's important to remember that [`char`] represents a Unicode Scalar
640 /// Value, and may not match your idea of what a 'character' is. Iteration
641 /// over grapheme clusters may be what you actually want.
643 /// [`char`]: primitive.char.html
650 /// let word = "goodbye";
652 /// let count = word.chars().count();
653 /// assert_eq!(7, count);
655 /// let mut chars = word.chars();
657 /// assert_eq!(Some('g'), chars.next());
658 /// assert_eq!(Some('o'), chars.next());
659 /// assert_eq!(Some('o'), chars.next());
660 /// assert_eq!(Some('d'), chars.next());
661 /// assert_eq!(Some('b'), chars.next());
662 /// assert_eq!(Some('y'), chars.next());
663 /// assert_eq!(Some('e'), chars.next());
665 /// assert_eq!(None, chars.next());
668 /// Remember, [`char`]s may not match your human intuition about characters:
673 /// let mut chars = y.chars();
675 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
676 /// assert_eq!(Some('\u{0306}'), chars.next());
678 /// assert_eq!(None, chars.next());
680 #[stable(feature = "rust1", since = "1.0.0")]
682 pub fn chars(&self) -> Chars {
683 core_str::StrExt::chars(self)
685 /// Returns an iterator over the [`char`]s of a string slice, and their
688 /// As a string slice consists of valid UTF-8, we can iterate through a
689 /// string slice by [`char`]. This method returns an iterator of both
690 /// these [`char`]s, as well as their byte positions.
692 /// The iterator yields tuples. The position is first, the [`char`] is
695 /// [`char`]: primitive.char.html
702 /// let word = "goodbye";
704 /// let count = word.char_indices().count();
705 /// assert_eq!(7, count);
707 /// let mut char_indices = word.char_indices();
709 /// assert_eq!(Some((0, 'g')), char_indices.next());
710 /// assert_eq!(Some((1, 'o')), char_indices.next());
711 /// assert_eq!(Some((2, 'o')), char_indices.next());
712 /// assert_eq!(Some((3, 'd')), char_indices.next());
713 /// assert_eq!(Some((4, 'b')), char_indices.next());
714 /// assert_eq!(Some((5, 'y')), char_indices.next());
715 /// assert_eq!(Some((6, 'e')), char_indices.next());
717 /// assert_eq!(None, char_indices.next());
720 /// Remember, [`char`]s may not match your human intuition about characters:
723 /// let yes = "y̆es";
725 /// let mut char_indices = yes.char_indices();
727 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
728 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
730 /// // note the 3 here - the last character took up two bytes
731 /// assert_eq!(Some((3, 'e')), char_indices.next());
732 /// assert_eq!(Some((4, 's')), char_indices.next());
734 /// assert_eq!(None, char_indices.next());
736 #[stable(feature = "rust1", since = "1.0.0")]
738 pub fn char_indices(&self) -> CharIndices {
739 core_str::StrExt::char_indices(self)
742 /// An iterator over the bytes of a string slice.
744 /// As a string slice consists of a sequence of bytes, we can iterate
745 /// through a string slice by byte. This method returns such an iterator.
752 /// let mut bytes = "bors".bytes();
754 /// assert_eq!(Some(b'b'), bytes.next());
755 /// assert_eq!(Some(b'o'), bytes.next());
756 /// assert_eq!(Some(b'r'), bytes.next());
757 /// assert_eq!(Some(b's'), bytes.next());
759 /// assert_eq!(None, bytes.next());
761 #[stable(feature = "rust1", since = "1.0.0")]
763 pub fn bytes(&self) -> Bytes {
764 core_str::StrExt::bytes(self)
767 /// Split a string slice by whitespace.
769 /// The iterator returned will return string slices that are sub-slices of
770 /// the original string slice, separated by any amount of whitespace.
772 /// 'Whitespace' is defined according to the terms of the Unicode Derived
773 /// Core Property `White_Space`.
780 /// let mut iter = "A few words".split_whitespace();
782 /// assert_eq!(Some("A"), iter.next());
783 /// assert_eq!(Some("few"), iter.next());
784 /// assert_eq!(Some("words"), iter.next());
786 /// assert_eq!(None, iter.next());
789 /// All kinds of whitespace are considered:
792 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
793 /// assert_eq!(Some("Mary"), iter.next());
794 /// assert_eq!(Some("had"), iter.next());
795 /// assert_eq!(Some("a"), iter.next());
796 /// assert_eq!(Some("little"), iter.next());
797 /// assert_eq!(Some("lamb"), iter.next());
799 /// assert_eq!(None, iter.next());
801 #[stable(feature = "split_whitespace", since = "1.1.0")]
803 pub fn split_whitespace(&self) -> SplitWhitespace {
804 UnicodeStr::split_whitespace(self)
807 /// An iterator over the lines of a string, as string slices.
809 /// Lines are ended with either a newline (`\n`) or a carriage return with
810 /// a line feed (`\r\n`).
812 /// The final line ending is optional.
819 /// let text = "foo\r\nbar\n\nbaz\n";
820 /// let mut lines = text.lines();
822 /// assert_eq!(Some("foo"), lines.next());
823 /// assert_eq!(Some("bar"), lines.next());
824 /// assert_eq!(Some(""), lines.next());
825 /// assert_eq!(Some("baz"), lines.next());
827 /// assert_eq!(None, lines.next());
830 /// The final line ending isn't required:
833 /// let text = "foo\nbar\n\r\nbaz";
834 /// let mut lines = text.lines();
836 /// assert_eq!(Some("foo"), lines.next());
837 /// assert_eq!(Some("bar"), lines.next());
838 /// assert_eq!(Some(""), lines.next());
839 /// assert_eq!(Some("baz"), lines.next());
841 /// assert_eq!(None, lines.next());
843 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn lines(&self) -> Lines {
846 core_str::StrExt::lines(self)
849 /// An iterator over the lines of a string.
850 #[stable(feature = "rust1", since = "1.0.0")]
851 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
854 pub fn lines_any(&self) -> LinesAny {
855 core_str::StrExt::lines_any(self)
858 /// Returns an iterator of `u16` over the string encoded as UTF-16.
865 /// let text = "Zażółć gęślą jaźń";
867 /// let utf8_len = text.len();
868 /// let utf16_len = text.encode_utf16().count();
870 /// assert!(utf16_len <= utf8_len);
872 #[stable(feature = "encode_utf16", since = "1.8.0")]
873 pub fn encode_utf16(&self) -> EncodeUtf16 {
874 EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
877 /// Returns `true` if the given pattern matches a sub-slice of
878 /// this string slice.
880 /// Returns `false` if it does not.
887 /// let bananas = "bananas";
889 /// assert!(bananas.contains("nana"));
890 /// assert!(!bananas.contains("apples"));
892 #[stable(feature = "rust1", since = "1.0.0")]
894 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
895 core_str::StrExt::contains(self, pat)
898 /// Returns `true` if the given pattern matches a prefix of this
901 /// Returns `false` if it does not.
908 /// let bananas = "bananas";
910 /// assert!(bananas.starts_with("bana"));
911 /// assert!(!bananas.starts_with("nana"));
913 #[stable(feature = "rust1", since = "1.0.0")]
914 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
915 core_str::StrExt::starts_with(self, pat)
918 /// Returns `true` if the given pattern matches a suffix of this
921 /// Returns `false` if it does not.
928 /// let bananas = "bananas";
930 /// assert!(bananas.ends_with("anas"));
931 /// assert!(!bananas.ends_with("nana"));
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
935 where P::Searcher: ReverseSearcher<'a>
937 core_str::StrExt::ends_with(self, pat)
940 /// Returns the byte index of the first character of this string slice that
941 /// matches the pattern.
943 /// Returns [`None`] if the pattern doesn't match.
945 /// The pattern can be a `&str`, [`char`], or a closure that determines if
946 /// a character matches.
948 /// [`char`]: primitive.char.html
949 /// [`None`]: option/enum.Option.html#variant.None
956 /// let s = "Löwe 老虎 Léopard";
958 /// assert_eq!(s.find('L'), Some(0));
959 /// assert_eq!(s.find('é'), Some(14));
960 /// assert_eq!(s.find("Léopard"), Some(13));
963 /// More complex patterns using point-free style and closures:
966 /// let s = "Löwe 老虎 Léopard";
968 /// assert_eq!(s.find(char::is_whitespace), Some(5));
969 /// assert_eq!(s.find(char::is_lowercase), Some(1));
970 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
971 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
974 /// Not finding the pattern:
977 /// let s = "Löwe 老虎 Léopard";
978 /// let x: &[_] = &['1', '2'];
980 /// assert_eq!(s.find(x), None);
982 #[stable(feature = "rust1", since = "1.0.0")]
984 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
985 core_str::StrExt::find(self, pat)
988 /// Returns the byte index of the last character of this string slice that
989 /// matches the pattern.
991 /// Returns [`None`] if the pattern doesn't match.
993 /// The pattern can be a `&str`, [`char`], or a closure that determines if
994 /// a character matches.
996 /// [`char`]: primitive.char.html
997 /// [`None`]: option/enum.Option.html#variant.None
1001 /// Simple patterns:
1004 /// let s = "Löwe 老虎 Léopard";
1006 /// assert_eq!(s.rfind('L'), Some(13));
1007 /// assert_eq!(s.rfind('é'), Some(14));
1010 /// More complex patterns with closures:
1013 /// let s = "Löwe 老虎 Léopard";
1015 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1016 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1019 /// Not finding the pattern:
1022 /// let s = "Löwe 老虎 Léopard";
1023 /// let x: &[_] = &['1', '2'];
1025 /// assert_eq!(s.rfind(x), None);
1027 #[stable(feature = "rust1", since = "1.0.0")]
1029 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1030 where P::Searcher: ReverseSearcher<'a>
1032 core_str::StrExt::rfind(self, pat)
1035 /// An iterator over substrings of this string slice, separated by
1036 /// characters matched by a pattern.
1038 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1041 /// # Iterator behavior
1043 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1044 /// allows a reverse search and forward/reverse search yields the same
1045 /// elements. This is true for, eg, [`char`] but not for `&str`.
1047 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1049 /// If the pattern allows a reverse search but its results might differ
1050 /// from a forward search, the [`rsplit`] method can be used.
1052 /// [`char`]: primitive.char.html
1053 /// [`rsplit`]: #method.rsplit
1057 /// Simple patterns:
1060 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1061 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1063 /// let v: Vec<&str> = "".split('X').collect();
1064 /// assert_eq!(v, [""]);
1066 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1067 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1069 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1070 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1072 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1073 /// assert_eq!(v, ["abc", "def", "ghi"]);
1075 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1076 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1079 /// A more complex pattern, using a closure:
1082 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1083 /// assert_eq!(v, ["abc", "def", "ghi"]);
1086 /// If a string contains multiple contiguous separators, you will end up
1087 /// with empty strings in the output:
1090 /// let x = "||||a||b|c".to_string();
1091 /// let d: Vec<_> = x.split('|').collect();
1093 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1096 /// Contiguous separators are separated by the empty string.
1099 /// let x = "(///)".to_string();
1100 /// let d: Vec<_> = x.split('/').collect();
1102 /// assert_eq!(d, &["(", "", "", ")"]);
1105 /// Separators at the start or end of a string are neighbored
1106 /// by empty strings.
1109 /// let d: Vec<_> = "010".split("0").collect();
1110 /// assert_eq!(d, &["", "1", ""]);
1113 /// When the empty string is used as a separator, it separates
1114 /// every character in the string, along with the beginning
1115 /// and end of the string.
1118 /// let f: Vec<_> = "rust".split("").collect();
1119 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1122 /// Contiguous separators can lead to possibly surprising behavior
1123 /// when whitespace is used as the separator. This code is correct:
1126 /// let x = " a b c".to_string();
1127 /// let d: Vec<_> = x.split(' ').collect();
1129 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1132 /// It does _not_ give you:
1135 /// assert_eq!(d, &["a", "b", "c"]);
1138 /// Use [`split_whitespace`] for this behavior.
1140 /// [`split_whitespace`]: #method.split_whitespace
1141 #[stable(feature = "rust1", since = "1.0.0")]
1143 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1144 core_str::StrExt::split(self, pat)
1147 /// An iterator over substrings of the given string slice, separated by
1148 /// characters matched by a pattern and yielded in reverse order.
1150 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1153 /// [`char`]: primitive.char.html
1155 /// # Iterator behavior
1157 /// The returned iterator requires that the pattern supports a reverse
1158 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1159 /// search yields the same elements.
1161 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1163 /// For iterating from the front, the [`split`] method can be used.
1165 /// [`split`]: #method.split
1169 /// Simple patterns:
1172 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1173 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1175 /// let v: Vec<&str> = "".rsplit('X').collect();
1176 /// assert_eq!(v, [""]);
1178 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1179 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1181 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1182 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1185 /// A more complex pattern, using a closure:
1188 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1189 /// assert_eq!(v, ["ghi", "def", "abc"]);
1191 #[stable(feature = "rust1", since = "1.0.0")]
1193 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1194 where P::Searcher: ReverseSearcher<'a>
1196 core_str::StrExt::rsplit(self, pat)
1199 /// An iterator over substrings of the given string slice, separated by
1200 /// characters matched by a pattern.
1202 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1205 /// Equivalent to [`split`], except that the trailing substring
1206 /// is skipped if empty.
1208 /// [`split`]: #method.split
1210 /// This method can be used for string data that is _terminated_,
1211 /// rather than _separated_ by a pattern.
1213 /// # Iterator behavior
1215 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1216 /// allows a reverse search and forward/reverse search yields the same
1217 /// elements. This is true for, eg, [`char`] but not for `&str`.
1219 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1220 /// [`char`]: primitive.char.html
1222 /// If the pattern allows a reverse search but its results might differ
1223 /// from a forward search, the [`rsplit_terminator`] method can be used.
1225 /// [`rsplit_terminator`]: #method.rsplit_terminator
1232 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1233 /// assert_eq!(v, ["A", "B"]);
1235 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1236 /// assert_eq!(v, ["A", "", "B", ""]);
1238 #[stable(feature = "rust1", since = "1.0.0")]
1240 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1241 core_str::StrExt::split_terminator(self, pat)
1244 /// An iterator over substrings of `self`, separated by characters
1245 /// matched by a pattern and yielded in reverse order.
1247 /// The pattern can be a simple `&str`, [`char`], or a closure that
1248 /// determines the split.
1249 /// Additional libraries might provide more complex patterns like
1250 /// regular expressions.
1252 /// [`char`]: primitive.char.html
1254 /// Equivalent to [`split`], except that the trailing substring is
1255 /// skipped if empty.
1257 /// [`split`]: #method.split
1259 /// This method can be used for string data that is _terminated_,
1260 /// rather than _separated_ by a pattern.
1262 /// # Iterator behavior
1264 /// The returned iterator requires that the pattern supports a
1265 /// reverse search, and it will be double ended if a forward/reverse
1266 /// search yields the same elements.
1268 /// For iterating from the front, the [`split_terminator`] method can be
1271 /// [`split_terminator`]: #method.split_terminator
1276 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1277 /// assert_eq!(v, ["B", "A"]);
1279 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1280 /// assert_eq!(v, ["", "B", "", "A"]);
1282 #[stable(feature = "rust1", since = "1.0.0")]
1284 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1285 where P::Searcher: ReverseSearcher<'a>
1287 core_str::StrExt::rsplit_terminator(self, pat)
1290 /// An iterator over substrings of the given string slice, separated by a
1291 /// pattern, restricted to returning at most `n` items.
1293 /// If `n` substrings are returned, the last substring (the `n`th substring)
1294 /// will contain the remainder of the string.
1296 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1299 /// [`char`]: primitive.char.html
1301 /// # Iterator behavior
1303 /// The returned iterator will not be double ended, because it is
1304 /// not efficient to support.
1306 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1309 /// [`rsplitn`]: #method.rsplitn
1313 /// Simple patterns:
1316 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1317 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1319 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1320 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1322 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1323 /// assert_eq!(v, ["abcXdef"]);
1325 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1326 /// assert_eq!(v, [""]);
1329 /// A more complex pattern, using a closure:
1332 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1333 /// assert_eq!(v, ["abc", "defXghi"]);
1335 #[stable(feature = "rust1", since = "1.0.0")]
1337 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1338 core_str::StrExt::splitn(self, n, pat)
1341 /// An iterator over substrings of this string slice, separated by a
1342 /// pattern, starting from the end of the string, restricted to returning
1343 /// at most `n` items.
1345 /// If `n` substrings are returned, the last substring (the `n`th substring)
1346 /// will contain the remainder of the string.
1348 /// The pattern can be a `&str`, [`char`], or a closure that
1349 /// determines the split.
1351 /// [`char`]: primitive.char.html
1353 /// # Iterator behavior
1355 /// The returned iterator will not be double ended, because it is not
1356 /// efficient to support.
1358 /// For splitting from the front, the [`splitn`] method can be used.
1360 /// [`splitn`]: #method.splitn
1364 /// Simple patterns:
1367 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1368 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1370 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1371 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1373 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1374 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1377 /// A more complex pattern, using a closure:
1380 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1381 /// assert_eq!(v, ["ghi", "abc1def"]);
1383 #[stable(feature = "rust1", since = "1.0.0")]
1385 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1386 where P::Searcher: ReverseSearcher<'a>
1388 core_str::StrExt::rsplitn(self, n, pat)
1391 /// An iterator over the disjoint matches of a pattern within the given string
1394 /// The pattern can be a `&str`, [`char`], or a closure that
1395 /// determines if a character matches.
1397 /// [`char`]: primitive.char.html
1399 /// # Iterator behavior
1401 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1402 /// allows a reverse search and forward/reverse search yields the same
1403 /// elements. This is true for, eg, [`char`] but not for `&str`.
1405 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1406 /// [`char`]: primitive.char.html
1408 /// If the pattern allows a reverse search but its results might differ
1409 /// from a forward search, the [`rmatches`] method can be used.
1411 /// [`rmatches`]: #method.rmatches
1418 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1419 /// assert_eq!(v, ["abc", "abc", "abc"]);
1421 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1422 /// assert_eq!(v, ["1", "2", "3"]);
1424 #[stable(feature = "str_matches", since = "1.2.0")]
1426 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1427 core_str::StrExt::matches(self, pat)
1430 /// An iterator over the disjoint matches of a pattern within this string slice,
1431 /// yielded in reverse order.
1433 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1434 /// a character matches.
1436 /// [`char`]: primitive.char.html
1438 /// # Iterator behavior
1440 /// The returned iterator requires that the pattern supports a reverse
1441 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1442 /// search yields the same elements.
1444 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1446 /// For iterating from the front, the [`matches`] method can be used.
1448 /// [`matches`]: #method.matches
1455 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1456 /// assert_eq!(v, ["abc", "abc", "abc"]);
1458 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1459 /// assert_eq!(v, ["3", "2", "1"]);
1461 #[stable(feature = "str_matches", since = "1.2.0")]
1463 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1464 where P::Searcher: ReverseSearcher<'a>
1466 core_str::StrExt::rmatches(self, pat)
1469 /// An iterator over the disjoint matches of a pattern within this string
1470 /// slice as well as the index that the match starts at.
1472 /// For matches of `pat` within `self` that overlap, only the indices
1473 /// corresponding to the first match are returned.
1475 /// The pattern can be a `&str`, [`char`], or a closure that determines
1476 /// if a character matches.
1478 /// [`char`]: primitive.char.html
1480 /// # Iterator behavior
1482 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1483 /// allows a reverse search and forward/reverse search yields the same
1484 /// elements. This is true for, eg, [`char`] but not for `&str`.
1486 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1488 /// If the pattern allows a reverse search but its results might differ
1489 /// from a forward search, the [`rmatch_indices`] method can be used.
1491 /// [`rmatch_indices`]: #method.rmatch_indices
1498 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1499 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1501 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1502 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1504 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1505 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1507 #[stable(feature = "str_match_indices", since = "1.5.0")]
1509 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1510 core_str::StrExt::match_indices(self, pat)
1513 /// An iterator over the disjoint matches of a pattern within `self`,
1514 /// yielded in reverse order along with the index of the match.
1516 /// For matches of `pat` within `self` that overlap, only the indices
1517 /// corresponding to the last match are returned.
1519 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1520 /// character matches.
1522 /// [`char`]: primitive.char.html
1524 /// # Iterator behavior
1526 /// The returned iterator requires that the pattern supports a reverse
1527 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1528 /// search yields the same elements.
1530 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1532 /// For iterating from the front, the [`match_indices`] method can be used.
1534 /// [`match_indices`]: #method.match_indices
1541 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1542 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1544 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1545 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1547 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1548 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1550 #[stable(feature = "str_match_indices", since = "1.5.0")]
1552 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1553 where P::Searcher: ReverseSearcher<'a>
1555 core_str::StrExt::rmatch_indices(self, pat)
1558 /// Returns a string slice with leading and trailing whitespace removed.
1560 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1561 /// Core Property `White_Space`.
1568 /// let s = " Hello\tworld\t";
1570 /// assert_eq!("Hello\tworld", s.trim());
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 pub fn trim(&self) -> &str {
1574 UnicodeStr::trim(self)
1577 /// Returns a string slice with leading whitespace removed.
1579 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1580 /// Core Property `White_Space`.
1582 /// # Text directionality
1584 /// A string is a sequence of bytes. 'Left' in this context means the first
1585 /// position of that byte string; for a language like Arabic or Hebrew
1586 /// which are 'right to left' rather than 'left to right', this will be
1587 /// the _right_ side, not the left.
1594 /// let s = " Hello\tworld\t";
1596 /// assert_eq!("Hello\tworld\t", s.trim_left());
1602 /// let s = " English";
1603 /// assert!(Some('E') == s.trim_left().chars().next());
1605 /// let s = " עברית";
1606 /// assert!(Some('ע') == s.trim_left().chars().next());
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 pub fn trim_left(&self) -> &str {
1610 UnicodeStr::trim_left(self)
1613 /// Returns a string slice with trailing whitespace removed.
1615 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1616 /// Core Property `White_Space`.
1618 /// # Text directionality
1620 /// A string is a sequence of bytes. 'Right' in this context means the last
1621 /// position of that byte string; for a language like Arabic or Hebrew
1622 /// which are 'right to left' rather than 'left to right', this will be
1623 /// the _left_ side, not the right.
1630 /// let s = " Hello\tworld\t";
1632 /// assert_eq!(" Hello\tworld", s.trim_right());
1638 /// let s = "English ";
1639 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1641 /// let s = "עברית ";
1642 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 pub fn trim_right(&self) -> &str {
1646 UnicodeStr::trim_right(self)
1649 /// Returns a string slice with all prefixes and suffixes that match a
1650 /// pattern repeatedly removed.
1652 /// The pattern can be a [`char`] or a closure that determines if a
1653 /// character matches.
1655 /// [`char`]: primitive.char.html
1659 /// Simple patterns:
1662 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1663 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1665 /// let x: &[_] = &['1', '2'];
1666 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1669 /// A more complex pattern, using a closure:
1672 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1676 where P::Searcher: DoubleEndedSearcher<'a>
1678 core_str::StrExt::trim_matches(self, pat)
1681 /// Returns a string slice with all prefixes that match a pattern
1682 /// repeatedly removed.
1684 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1685 /// a character matches.
1687 /// [`char`]: primitive.char.html
1689 /// # Text directionality
1691 /// A string is a sequence of bytes. 'Left' in this context means the first
1692 /// position of that byte string; for a language like Arabic or Hebrew
1693 /// which are 'right to left' rather than 'left to right', this will be
1694 /// the _right_ side, not the left.
1701 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1702 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1704 /// let x: &[_] = &['1', '2'];
1705 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1707 #[stable(feature = "rust1", since = "1.0.0")]
1708 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1709 core_str::StrExt::trim_left_matches(self, pat)
1712 /// Returns a string slice with all suffixes that match a pattern
1713 /// repeatedly removed.
1715 /// The pattern can be a `&str`, [`char`], or a closure that
1716 /// determines if a character matches.
1718 /// [`char`]: primitive.char.html
1720 /// # Text directionality
1722 /// A string is a sequence of bytes. 'Right' in this context means the last
1723 /// position of that byte string; for a language like Arabic or Hebrew
1724 /// which are 'right to left' rather than 'left to right', this will be
1725 /// the _left_ side, not the right.
1729 /// Simple patterns:
1732 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1733 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1735 /// let x: &[_] = &['1', '2'];
1736 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1739 /// A more complex pattern, using a closure:
1742 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1746 where P::Searcher: ReverseSearcher<'a>
1748 core_str::StrExt::trim_right_matches(self, pat)
1751 /// Parses this string slice into another type.
1753 /// Because `parse` is so general, it can cause problems with type
1754 /// inference. As such, `parse` is one of the few times you'll see
1755 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1756 /// helps the inference algorithm understand specifically which type
1757 /// you're trying to parse into.
1759 /// `parse` can parse any type that implements the [`FromStr`] trait.
1761 /// [`FromStr`]: str/trait.FromStr.html
1765 /// Will return [`Err`] if it's not possible to parse this string slice into
1766 /// the desired type.
1768 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1775 /// let four: u32 = "4".parse().unwrap();
1777 /// assert_eq!(4, four);
1780 /// Using the 'turbofish' instead of annotating `four`:
1783 /// let four = "4".parse::<u32>();
1785 /// assert_eq!(Ok(4), four);
1788 /// Failing to parse:
1791 /// let nope = "j".parse::<u32>();
1793 /// assert!(nope.is_err());
1796 #[stable(feature = "rust1", since = "1.0.0")]
1797 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1798 core_str::StrExt::parse(self)
1801 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
1808 /// let s = "this is a string";
1809 /// let boxed_str = s.to_owned().into_boxed_str();
1810 /// let boxed_bytes = boxed_str.into_boxed_bytes();
1811 /// assert_eq!(*boxed_bytes, *s.as_bytes());
1813 #[stable(feature = "str_box_extras", since = "1.20.0")]
1814 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
1818 /// Replaces all matches of a pattern with another string.
1820 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1821 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1822 /// replaces them with the replacement string slice.
1824 /// [`String`]: string/struct.String.html
1831 /// let s = "this is old";
1833 /// assert_eq!("this is new", s.replace("old", "new"));
1836 /// When the pattern doesn't match:
1839 /// let s = "this is old";
1840 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1842 #[stable(feature = "rust1", since = "1.0.0")]
1844 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1845 let mut result = String::new();
1846 let mut last_end = 0;
1847 for (start, part) in self.match_indices(from) {
1848 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1849 result.push_str(to);
1850 last_end = start + part.len();
1852 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1856 /// Replaces first N matches of a pattern with another string.
1858 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1859 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1860 /// replaces them with the replacement string slice at most `count` times.
1862 /// [`String`]: string/struct.String.html
1869 /// let s = "foo foo 123 foo";
1870 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1871 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1872 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1875 /// When the pattern doesn't match:
1878 /// let s = "this is old";
1879 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1881 #[stable(feature = "str_replacen", since = "1.16.0")]
1882 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1883 // Hope to reduce the times of re-allocation
1884 let mut result = String::with_capacity(32);
1885 let mut last_end = 0;
1886 for (start, part) in self.match_indices(pat).take(count) {
1887 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1888 result.push_str(to);
1889 last_end = start + part.len();
1891 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1895 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1897 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1900 /// Since some characters can expand into multiple characters when changing
1901 /// the case, this function returns a [`String`] instead of modifying the
1902 /// parameter in-place.
1904 /// [`String`]: string/struct.String.html
1911 /// let s = "HELLO";
1913 /// assert_eq!("hello", s.to_lowercase());
1916 /// A tricky example, with sigma:
1919 /// let sigma = "Σ";
1921 /// assert_eq!("σ", sigma.to_lowercase());
1923 /// // but at the end of a word, it's ς, not σ:
1924 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1926 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1929 /// Languages without case are not changed:
1932 /// let new_year = "农历新年";
1934 /// assert_eq!(new_year, new_year.to_lowercase());
1936 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1937 pub fn to_lowercase(&self) -> String {
1938 let mut s = String::with_capacity(self.len());
1939 for (i, c) in self[..].char_indices() {
1941 // Σ maps to σ, except at the end of a word where it maps to ς.
1942 // This is the only conditional (contextual) but language-independent mapping
1943 // in `SpecialCasing.txt`,
1944 // so hard-code it rather than have a generic "condition" mechanism.
1945 // See https://github.com/rust-lang/rust/issues/26035
1946 map_uppercase_sigma(self, i, &mut s)
1948 s.extend(c.to_lowercase());
1953 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1954 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1955 // for the definition of `Final_Sigma`.
1956 debug_assert!('Σ'.len_utf8() == 2);
1957 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1958 !case_ignoreable_then_cased(from[i + 2..].chars());
1959 to.push_str(if is_word_final { "ς" } else { "σ" });
1962 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1963 use std_unicode::derived_property::{Cased, Case_Ignorable};
1964 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1965 Some(c) => Cased(c),
1971 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1973 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1976 /// Since some characters can expand into multiple characters when changing
1977 /// the case, this function returns a [`String`] instead of modifying the
1978 /// parameter in-place.
1980 /// [`String`]: string/struct.String.html
1987 /// let s = "hello";
1989 /// assert_eq!("HELLO", s.to_uppercase());
1992 /// Scripts without case are not changed:
1995 /// let new_year = "农历新年";
1997 /// assert_eq!(new_year, new_year.to_uppercase());
1999 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
2000 pub fn to_uppercase(&self) -> String {
2001 let mut s = String::with_capacity(self.len());
2002 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
2006 /// Escapes each char in `s` with [`char::escape_debug`].
2008 /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
2009 #[unstable(feature = "str_escape",
2010 reason = "return type may change to be an iterator",
2012 pub fn escape_debug(&self) -> String {
2013 self.chars().flat_map(|c| c.escape_debug()).collect()
2016 /// Escapes each char in `s` with [`char::escape_default`].
2018 /// [`char::escape_default`]: primitive.char.html#method.escape_default
2019 #[unstable(feature = "str_escape",
2020 reason = "return type may change to be an iterator",
2022 pub fn escape_default(&self) -> String {
2023 self.chars().flat_map(|c| c.escape_default()).collect()
2026 /// Escapes each char in `s` with [`char::escape_unicode`].
2028 /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
2029 #[unstable(feature = "str_escape",
2030 reason = "return type may change to be an iterator",
2032 pub fn escape_unicode(&self) -> String {
2033 self.chars().flat_map(|c| c.escape_unicode()).collect()
2036 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
2038 /// [`String`]: string/struct.String.html
2039 /// [`Box<str>`]: boxed/struct.Box.html
2046 /// let string = String::from("birthday gift");
2047 /// let boxed_str = string.clone().into_boxed_str();
2049 /// assert_eq!(boxed_str.into_string(), string);
2051 #[stable(feature = "box_str", since = "1.4.0")]
2052 pub fn into_string(self: Box<str>) -> String {
2053 let slice = Box::<[u8]>::from(self);
2054 unsafe { String::from_utf8_unchecked(slice.into_vec()) }
2057 /// Create a [`String`] by repeating a string `n` times.
2059 /// [`String`]: string/struct.String.html
2066 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
2068 #[stable(feature = "repeat_str", since = "1.16.0")]
2069 pub fn repeat(&self, n: usize) -> String {
2071 return String::new();
2074 // If `n` is larger than zero, it can be split as
2075 // `n = 2^expn + rem (2^expn > rem, expn >= 0, rem >= 0)`.
2076 // `2^expn` is the number represented by the leftmost '1' bit of `n`,
2077 // and `rem` is the remaining part of `n`.
2079 // Using `Vec` to access `set_len()`.
2080 let mut buf = Vec::with_capacity(self.len() * n);
2082 // `2^expn` repetition is done by doubling `buf` `expn`-times.
2083 buf.extend(self.as_bytes());
2086 // If `m > 0`, there are remaining bits up to the leftmost '1'.
2088 // `buf.extend(buf)`:
2090 ptr::copy_nonoverlapping(
2092 (buf.as_mut_ptr() as *mut u8).add(buf.len()),
2095 // `buf` has capacity of `self.len() * n`.
2096 let buf_len = buf.len();
2097 buf.set_len(buf_len * 2);
2104 // `rem` (`= n - 2^expn`) repetition is done by copying
2105 // first `rem` repetitions from `buf` itself.
2106 let rem_len = self.len() * n - buf.len(); // `self.len() * rem`
2108 // `buf.extend(buf[0 .. rem_len])`:
2110 // This is non-overlapping since `2^expn > rem`.
2111 ptr::copy_nonoverlapping(
2113 (buf.as_mut_ptr() as *mut u8).add(buf.len()),
2116 // `buf.len() + rem_len` equals to `buf.capacity()` (`= self.len() * n`).
2117 let buf_cap = buf.capacity();
2118 buf.set_len(buf_cap);
2122 unsafe { String::from_utf8_unchecked(buf) }
2125 /// Checks if all characters in this string are within the ASCII range.
2130 /// let ascii = "hello!\n";
2131 /// let non_ascii = "Grüße, Jürgen ❤";
2133 /// assert!(ascii.is_ascii());
2134 /// assert!(!non_ascii.is_ascii());
2136 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2138 pub fn is_ascii(&self) -> bool {
2139 // We can treat each byte as character here: all multibyte characters
2140 // start with a byte that is not in the ascii range, so we will stop
2142 self.bytes().all(|b| b.is_ascii())
2145 /// Returns a copy of this string where each character is mapped to its
2146 /// ASCII upper case equivalent.
2148 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2149 /// but non-ASCII letters are unchanged.
2151 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2153 /// To uppercase ASCII characters in addition to non-ASCII characters, use
2154 /// [`to_uppercase`].
2159 /// let s = "Grüße, Jürgen ❤";
2161 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
2164 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2165 /// [`to_uppercase`]: #method.to_uppercase
2166 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2168 pub fn to_ascii_uppercase(&self) -> String {
2169 let mut bytes = self.as_bytes().to_vec();
2170 bytes.make_ascii_uppercase();
2171 // make_ascii_uppercase() preserves the UTF-8 invariant.
2172 unsafe { String::from_utf8_unchecked(bytes) }
2175 /// Returns a copy of this string where each character is mapped to its
2176 /// ASCII lower case equivalent.
2178 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2179 /// but non-ASCII letters are unchanged.
2181 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2183 /// To lowercase ASCII characters in addition to non-ASCII characters, use
2184 /// [`to_lowercase`].
2189 /// let s = "Grüße, Jürgen ❤";
2191 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
2194 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2195 /// [`to_lowercase`]: #method.to_lowercase
2196 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2198 pub fn to_ascii_lowercase(&self) -> String {
2199 let mut bytes = self.as_bytes().to_vec();
2200 bytes.make_ascii_lowercase();
2201 // make_ascii_lowercase() preserves the UTF-8 invariant.
2202 unsafe { String::from_utf8_unchecked(bytes) }
2205 /// Checks that two strings are an ASCII case-insensitive match.
2207 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2208 /// but without allocating and copying temporaries.
2213 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2214 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2215 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2217 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2219 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2220 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2223 /// Converts this string to its ASCII upper case equivalent in-place.
2225 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2226 /// but non-ASCII letters are unchanged.
2228 /// To return a new uppercased value without modifying the existing one, use
2229 /// [`to_ascii_uppercase`].
2231 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2232 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2233 pub fn make_ascii_uppercase(&mut self) {
2234 let me = unsafe { self.as_bytes_mut() };
2235 me.make_ascii_uppercase()
2238 /// Converts this string to its ASCII lower case equivalent in-place.
2240 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2241 /// but non-ASCII letters are unchanged.
2243 /// To return a new lowercased value without modifying the existing one, use
2244 /// [`to_ascii_lowercase`].
2246 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2247 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2248 pub fn make_ascii_lowercase(&mut self) {
2249 let me = unsafe { self.as_bytes_mut() };
2250 me.make_ascii_lowercase()
2254 /// Converts a boxed slice of bytes to a boxed string slice without checking
2255 /// that the string contains valid UTF-8.
2262 /// let smile_utf8 = Box::new([226, 152, 186]);
2263 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
2265 /// assert_eq!("☺", &*smile);
2267 #[stable(feature = "str_box_extras", since = "1.20.0")]
2268 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
2269 Box::from_raw(Box::into_raw(v) as *mut str)