1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Unicode string slices.
13 //! The `&str` type is one of the two main string types, the other being `String`.
14 //! Unlike its `String` counterpart, its contents are borrowed.
18 //! A basic string declaration of `&str` type:
21 //! let hello_world = "Hello, World!";
24 //! Here we have declared a string literal, also known as a string slice.
25 //! String literals have a static lifetime, which means the string `hello_world`
26 //! is guaranteed to be valid for the duration of the entire program.
27 //! We can explicitly specify `hello_world`'s lifetime as well:
30 //! let hello_world: &'static str = "Hello, world!";
33 //! *[See also the `str` primitive type](../../std/primitive.str.html).*
35 #![stable(feature = "rust1", since = "1.0.0")]
37 // Many of the usings in this module are only used in the test configuration.
38 // It's cleaner to just turn off the unused_imports warning than to fix them.
39 #![allow(unused_imports)]
42 use core::str as core_str;
43 use core::str::pattern::Pattern;
44 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
46 use core::iter::FusedIterator;
47 use std_unicode::str::{UnicodeStr, Utf16Encoder};
49 use vec_deque::VecDeque;
50 use borrow::{Borrow, ToOwned};
54 use slice::{SliceConcatExt, SliceIndex};
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub use core::str::{FromStr, Utf8Error};
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub use core::str::{Lines, LinesAny};
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub use core::str::{Split, RSplit};
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub use core::str::{SplitN, RSplitN};
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub use core::str::{SplitTerminator, RSplitTerminator};
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use core::str::{Matches, RMatches};
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub use core::str::{MatchIndices, RMatchIndices};
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub use core::str::{from_utf8_unchecked, 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;
81 #[unstable(feature = "slice_concat_ext",
82 reason = "trait should not have to exist",
84 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
87 fn concat(&self) -> String {
92 // `len` calculation may overflow but push_str will check boundaries
93 let len = self.iter().map(|s| s.borrow().len()).sum();
94 let mut result = String::with_capacity(len);
97 result.push_str(s.borrow())
103 fn join(&self, sep: &str) -> String {
105 return String::new();
110 return self.concat();
113 // this is wrong without the guarantee that `self` is non-empty
114 // `len` calculation may overflow but push_str but will check boundaries
115 let len = sep.len() * (self.len() - 1) +
116 self.iter().map(|s| s.borrow().len()).sum::<usize>();
117 let mut result = String::with_capacity(len);
118 let mut first = true;
124 result.push_str(sep);
126 result.push_str(s.borrow());
131 fn connect(&self, sep: &str) -> String {
136 /// An iterator of [`u16`] over the string encoded as UTF-16.
138 /// [`u16`]: ../../std/primitive.u16.html
140 /// This struct is created by the [`encode_utf16`] method on [`str`].
141 /// See its documentation for more.
143 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
144 /// [`str`]: ../../std/primitive.str.html
146 #[stable(feature = "encode_utf16", since = "1.8.0")]
147 pub struct EncodeUtf16<'a> {
148 encoder: Utf16Encoder<Chars<'a>>,
151 #[stable(feature = "collection_debug", since = "1.17.0")]
152 impl<'a> fmt::Debug for EncodeUtf16<'a> {
153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154 f.pad("EncodeUtf16 { .. }")
158 #[stable(feature = "encode_utf16", since = "1.8.0")]
159 impl<'a> Iterator for EncodeUtf16<'a> {
163 fn next(&mut self) -> Option<u16> {
168 fn size_hint(&self) -> (usize, Option<usize>) {
169 self.encoder.size_hint()
173 #[unstable(feature = "fused", issue = "35602")]
174 impl<'a> FusedIterator for EncodeUtf16<'a> {}
176 // Return the initial codepoint accumulator for the first byte.
177 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
178 // for width 3, and 3 bits for width 4
179 macro_rules! utf8_first_byte {
180 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
183 // return the value of $ch updated with continuation byte $byte
184 macro_rules! utf8_acc_cont_byte {
185 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
188 #[stable(feature = "rust1", since = "1.0.0")]
189 impl Borrow<str> for String {
191 fn borrow(&self) -> &str {
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl ToOwned for str {
199 fn to_owned(&self) -> String {
200 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
203 fn clone_into(&self, target: &mut String) {
204 let mut b = mem::replace(target, String::new()).into_bytes();
205 self.as_bytes().clone_into(&mut b);
206 *target = unsafe { String::from_utf8_unchecked(b) }
210 /// Methods for string slices.
214 /// Returns the length of `self`.
216 /// This length is in bytes, not [`char`]s or graphemes. In other words,
217 /// it may not be what a human considers the length of the string.
219 /// [`char`]: primitive.char.html
226 /// let len = "foo".len();
227 /// assert_eq!(3, len);
229 /// let len = "ƒoo".len(); // fancy f!
230 /// assert_eq!(4, len);
232 #[stable(feature = "rust1", since = "1.0.0")]
234 pub fn len(&self) -> usize {
235 core_str::StrExt::len(self)
238 /// Returns `true` if `self` has a length of zero bytes.
246 /// assert!(s.is_empty());
248 /// let s = "not empty";
249 /// assert!(!s.is_empty());
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub fn is_empty(&self) -> bool {
254 core_str::StrExt::is_empty(self)
257 /// Checks that `index`-th byte lies at the start and/or end of a
258 /// UTF-8 code point sequence.
260 /// The start and end of the string (when `index == self.len()`) are
264 /// Returns `false` if `index` is greater than `self.len()`.
269 /// let s = "Löwe 老虎 Léopard";
270 /// assert!(s.is_char_boundary(0));
272 /// assert!(s.is_char_boundary(6));
273 /// assert!(s.is_char_boundary(s.len()));
275 /// // second byte of `ö`
276 /// assert!(!s.is_char_boundary(2));
278 /// // third byte of `老`
279 /// assert!(!s.is_char_boundary(8));
281 #[stable(feature = "is_char_boundary", since = "1.9.0")]
283 pub fn is_char_boundary(&self, index: usize) -> bool {
284 core_str::StrExt::is_char_boundary(self, index)
287 /// Converts a string slice to a byte slice.
294 /// let bytes = "bors".as_bytes();
295 /// assert_eq!(b"bors", bytes);
297 #[stable(feature = "rust1", since = "1.0.0")]
299 pub fn as_bytes(&self) -> &[u8] {
300 core_str::StrExt::as_bytes(self)
303 /// Converts a mutable string slice to a mutable byte slice.
304 #[unstable(feature = "str_mut_extras", issue = "41119")]
306 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
307 core_str::StrExt::as_bytes_mut(self)
310 /// Converts a string slice to a raw pointer.
312 /// As string slices are a slice of bytes, the raw pointer points to a
313 /// [`u8`]. This pointer will be pointing to the first byte of the string
316 /// [`u8`]: primitive.u8.html
324 /// let ptr = s.as_ptr();
326 #[stable(feature = "rust1", since = "1.0.0")]
328 pub fn as_ptr(&self) -> *const u8 {
329 core_str::StrExt::as_ptr(self)
332 /// Returns a subslice of `str`.
334 /// This is the non-panicking alternative to indexing the `str`. Returns
335 /// [`None`] whenever equivalent indexing operation would panic.
337 /// [`None`]: option/enum.Option.html#variant.None
342 /// # #![feature(str_checked_slicing)]
344 /// assert_eq!(Some("🗻"), v.get(0..4));
345 /// assert!(v.get(1..).is_none());
346 /// assert!(v.get(..8).is_none());
347 /// assert!(v.get(..42).is_none());
349 #[unstable(feature = "str_checked_slicing", issue = "39932")]
351 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
352 core_str::StrExt::get(self, i)
355 /// Returns a mutable subslice of `str`.
357 /// This is the non-panicking alternative to indexing the `str`. Returns
358 /// [`None`] whenever equivalent indexing operation would panic.
360 /// [`None`]: option/enum.Option.html#variant.None
365 /// # #![feature(str_checked_slicing)]
366 /// let mut v = String::from("🗻∈🌏");
367 /// assert_eq!(Some("🗻"), v.get_mut(0..4).map(|v| &*v));
368 /// assert!(v.get_mut(1..).is_none());
369 /// assert!(v.get_mut(..8).is_none());
370 /// assert!(v.get_mut(..42).is_none());
372 #[unstable(feature = "str_checked_slicing", issue = "39932")]
374 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
375 core_str::StrExt::get_mut(self, i)
378 /// Returns a unchecked subslice of `str`.
380 /// This is the unchecked alternative to indexing the `str`.
384 /// Callers of this function are responsible that these preconditions are
387 /// * The starting index must come before the ending index;
388 /// * Indexes must be within bounds of the original slice;
389 /// * Indexes must lie on UTF-8 sequence boundaries.
391 /// Failing that, the returned string slice may reference invalid memory or
392 /// violate the invariants communicated by the `str` type.
397 /// # #![feature(str_checked_slicing)]
400 /// assert_eq!("🗻", v.get_unchecked(0..4));
401 /// assert_eq!("∈", v.get_unchecked(4..7));
402 /// assert_eq!("🌏", v.get_unchecked(7..11));
405 #[unstable(feature = "str_checked_slicing", issue = "39932")]
407 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
408 core_str::StrExt::get_unchecked(self, i)
411 /// Returns a mutable, unchecked subslice of `str`.
413 /// This is the unchecked alternative to indexing the `str`.
417 /// Callers of this function are responsible that these preconditions are
420 /// * The starting index must come before the ending index;
421 /// * Indexes must be within bounds of the original slice;
422 /// * Indexes must lie on UTF-8 sequence boundaries.
424 /// Failing that, the returned string slice may reference invalid memory or
425 /// violate the invariants communicated by the `str` type.
430 /// # #![feature(str_checked_slicing)]
431 /// let mut v = String::from("🗻∈🌏");
433 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
434 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
435 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
438 #[unstable(feature = "str_checked_slicing", issue = "39932")]
440 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
441 core_str::StrExt::get_unchecked_mut(self, i)
444 /// Creates a string slice from another string slice, bypassing safety
447 /// This new slice goes from `begin` to `end`, including `begin` but
450 /// To get a mutable string slice instead, see the
451 /// [`slice_mut_unchecked`] method.
453 /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
457 /// Callers of this function are responsible that three preconditions are
460 /// * `begin` must come before `end`.
461 /// * `begin` and `end` must be byte positions within the string slice.
462 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
469 /// let s = "Löwe 老虎 Léopard";
472 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
475 /// let s = "Hello, world!";
478 /// assert_eq!("world", s.slice_unchecked(7, 12));
481 #[stable(feature = "rust1", since = "1.0.0")]
483 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
484 core_str::StrExt::slice_unchecked(self, begin, end)
487 /// Creates a string slice from another string slice, bypassing safety
490 /// This new slice goes from `begin` to `end`, including `begin` but
493 /// To get an immutable string slice instead, see the
494 /// [`slice_unchecked`] method.
496 /// [`slice_unchecked`]: #method.slice_unchecked
500 /// Callers of this function are responsible that three preconditions are
503 /// * `begin` must come before `end`.
504 /// * `begin` and `end` must be byte positions within the string slice.
505 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
506 #[stable(feature = "str_slice_mut", since = "1.5.0")]
508 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
509 core_str::StrExt::slice_mut_unchecked(self, begin, end)
512 /// Divide one string slice into two at an index.
514 /// The argument, `mid`, should be a byte offset from the start of the
515 /// string. It must also be on the boundary of a UTF-8 code point.
517 /// The two slices returned go from the start of the string slice to `mid`,
518 /// and from `mid` to the end of the string slice.
520 /// To get mutable string slices instead, see the [`split_at_mut`]
523 /// [`split_at_mut`]: #method.split_at_mut
527 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
528 /// beyond the last code point of the string slice.
535 /// let s = "Per Martin-Löf";
537 /// let (first, last) = s.split_at(3);
539 /// assert_eq!("Per", first);
540 /// assert_eq!(" Martin-Löf", last);
543 #[stable(feature = "str_split_at", since = "1.4.0")]
544 pub fn split_at(&self, mid: usize) -> (&str, &str) {
545 core_str::StrExt::split_at(self, mid)
548 /// Divide one mutable string slice into two at an index.
550 /// The argument, `mid`, should be a byte offset from the start of the
551 /// string. It must also be on the boundary of a UTF-8 code point.
553 /// The two slices returned go from the start of the string slice to `mid`,
554 /// and from `mid` to the end of the string slice.
556 /// To get immutable string slices instead, see the [`split_at`] method.
558 /// [`split_at`]: #method.split_at
562 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
563 /// beyond the last code point of the string slice.
570 /// let mut s = "Per Martin-Löf".to_string();
572 /// let (first, last) = s.split_at_mut(3);
574 /// assert_eq!("Per", first);
575 /// assert_eq!(" Martin-Löf", last);
578 #[stable(feature = "str_split_at", since = "1.4.0")]
579 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
580 core_str::StrExt::split_at_mut(self, mid)
583 /// Returns an iterator over the [`char`]s of a string slice.
585 /// As a string slice consists of valid UTF-8, we can iterate through a
586 /// string slice by [`char`]. This method returns such an iterator.
588 /// It's important to remember that [`char`] represents a Unicode Scalar
589 /// Value, and may not match your idea of what a 'character' is. Iteration
590 /// over grapheme clusters may be what you actually want.
592 /// [`char`]: primitive.char.html
599 /// let word = "goodbye";
601 /// let count = word.chars().count();
602 /// assert_eq!(7, count);
604 /// let mut chars = word.chars();
606 /// assert_eq!(Some('g'), chars.next());
607 /// assert_eq!(Some('o'), chars.next());
608 /// assert_eq!(Some('o'), chars.next());
609 /// assert_eq!(Some('d'), chars.next());
610 /// assert_eq!(Some('b'), chars.next());
611 /// assert_eq!(Some('y'), chars.next());
612 /// assert_eq!(Some('e'), chars.next());
614 /// assert_eq!(None, chars.next());
617 /// Remember, [`char`]s may not match your human intuition about characters:
622 /// let mut chars = y.chars();
624 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
625 /// assert_eq!(Some('\u{0306}'), chars.next());
627 /// assert_eq!(None, chars.next());
629 #[stable(feature = "rust1", since = "1.0.0")]
631 pub fn chars(&self) -> Chars {
632 core_str::StrExt::chars(self)
634 /// Returns an iterator over the [`char`]s of a string slice, and their
637 /// As a string slice consists of valid UTF-8, we can iterate through a
638 /// string slice by [`char`]. This method returns an iterator of both
639 /// these [`char`]s, as well as their byte positions.
641 /// The iterator yields tuples. The position is first, the [`char`] is
644 /// [`char`]: primitive.char.html
651 /// let word = "goodbye";
653 /// let count = word.char_indices().count();
654 /// assert_eq!(7, count);
656 /// let mut char_indices = word.char_indices();
658 /// assert_eq!(Some((0, 'g')), char_indices.next());
659 /// assert_eq!(Some((1, 'o')), char_indices.next());
660 /// assert_eq!(Some((2, 'o')), char_indices.next());
661 /// assert_eq!(Some((3, 'd')), char_indices.next());
662 /// assert_eq!(Some((4, 'b')), char_indices.next());
663 /// assert_eq!(Some((5, 'y')), char_indices.next());
664 /// assert_eq!(Some((6, 'e')), char_indices.next());
666 /// assert_eq!(None, char_indices.next());
669 /// Remember, [`char`]s may not match your human intuition about characters:
674 /// let mut char_indices = y.char_indices();
676 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
677 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
679 /// assert_eq!(None, char_indices.next());
681 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn char_indices(&self) -> CharIndices {
684 core_str::StrExt::char_indices(self)
687 /// An iterator over the bytes of a string slice.
689 /// As a string slice consists of a sequence of bytes, we can iterate
690 /// through a string slice by byte. This method returns such an iterator.
697 /// let mut bytes = "bors".bytes();
699 /// assert_eq!(Some(b'b'), bytes.next());
700 /// assert_eq!(Some(b'o'), bytes.next());
701 /// assert_eq!(Some(b'r'), bytes.next());
702 /// assert_eq!(Some(b's'), bytes.next());
704 /// assert_eq!(None, bytes.next());
706 #[stable(feature = "rust1", since = "1.0.0")]
708 pub fn bytes(&self) -> Bytes {
709 core_str::StrExt::bytes(self)
712 /// Split a string slice by whitespace.
714 /// The iterator returned will return string slices that are sub-slices of
715 /// the original string slice, separated by any amount of whitespace.
717 /// 'Whitespace' is defined according to the terms of the Unicode Derived
718 /// Core Property `White_Space`.
725 /// let mut iter = "A few words".split_whitespace();
727 /// assert_eq!(Some("A"), iter.next());
728 /// assert_eq!(Some("few"), iter.next());
729 /// assert_eq!(Some("words"), iter.next());
731 /// assert_eq!(None, iter.next());
734 /// All kinds of whitespace are considered:
737 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
738 /// assert_eq!(Some("Mary"), iter.next());
739 /// assert_eq!(Some("had"), iter.next());
740 /// assert_eq!(Some("a"), iter.next());
741 /// assert_eq!(Some("little"), iter.next());
742 /// assert_eq!(Some("lamb"), iter.next());
744 /// assert_eq!(None, iter.next());
746 #[stable(feature = "split_whitespace", since = "1.1.0")]
748 pub fn split_whitespace(&self) -> SplitWhitespace {
749 UnicodeStr::split_whitespace(self)
752 /// An iterator over the lines of a string, as string slices.
754 /// Lines are ended with either a newline (`\n`) or a carriage return with
755 /// a line feed (`\r\n`).
757 /// The final line ending is optional.
764 /// let text = "foo\r\nbar\n\nbaz\n";
765 /// let mut lines = text.lines();
767 /// assert_eq!(Some("foo"), lines.next());
768 /// assert_eq!(Some("bar"), lines.next());
769 /// assert_eq!(Some(""), lines.next());
770 /// assert_eq!(Some("baz"), lines.next());
772 /// assert_eq!(None, lines.next());
775 /// The final line ending isn't required:
778 /// let text = "foo\nbar\n\r\nbaz";
779 /// let mut lines = text.lines();
781 /// assert_eq!(Some("foo"), lines.next());
782 /// assert_eq!(Some("bar"), lines.next());
783 /// assert_eq!(Some(""), lines.next());
784 /// assert_eq!(Some("baz"), lines.next());
786 /// assert_eq!(None, lines.next());
788 #[stable(feature = "rust1", since = "1.0.0")]
790 pub fn lines(&self) -> Lines {
791 core_str::StrExt::lines(self)
794 /// An iterator over the lines of a string.
795 #[stable(feature = "rust1", since = "1.0.0")]
796 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
799 pub fn lines_any(&self) -> LinesAny {
800 core_str::StrExt::lines_any(self)
803 /// Returns an iterator of `u16` over the string encoded as UTF-16.
804 #[stable(feature = "encode_utf16", since = "1.8.0")]
805 pub fn encode_utf16(&self) -> EncodeUtf16 {
806 EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
809 /// Returns `true` if the given pattern matches a sub-slice of
810 /// this string slice.
812 /// Returns `false` if it does not.
819 /// let bananas = "bananas";
821 /// assert!(bananas.contains("nana"));
822 /// assert!(!bananas.contains("apples"));
824 #[stable(feature = "rust1", since = "1.0.0")]
825 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
826 core_str::StrExt::contains(self, pat)
829 /// Returns `true` if the given pattern matches a prefix of this
832 /// Returns `false` if it does not.
839 /// let bananas = "bananas";
841 /// assert!(bananas.starts_with("bana"));
842 /// assert!(!bananas.starts_with("nana"));
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
846 core_str::StrExt::starts_with(self, pat)
849 /// Returns `true` if the given pattern matches a suffix of this
852 /// Returns `false` if it does not.
859 /// let bananas = "bananas";
861 /// assert!(bananas.ends_with("anas"));
862 /// assert!(!bananas.ends_with("nana"));
864 #[stable(feature = "rust1", since = "1.0.0")]
865 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
866 where P::Searcher: ReverseSearcher<'a>
868 core_str::StrExt::ends_with(self, pat)
871 /// Returns the byte index of the first character of this string slice that
872 /// matches the pattern.
874 /// Returns [`None`] if the pattern doesn't match.
876 /// The pattern can be a `&str`, [`char`], or a closure that determines if
877 /// a character matches.
879 /// [`char`]: primitive.char.html
880 /// [`None`]: option/enum.Option.html#variant.None
887 /// let s = "Löwe 老虎 Léopard";
889 /// assert_eq!(s.find('L'), Some(0));
890 /// assert_eq!(s.find('é'), Some(14));
891 /// assert_eq!(s.find("Léopard"), Some(13));
894 /// More complex patterns with closures:
897 /// let s = "Löwe 老虎 Léopard";
899 /// assert_eq!(s.find(char::is_whitespace), Some(5));
900 /// assert_eq!(s.find(char::is_lowercase), Some(1));
903 /// Not finding the pattern:
906 /// let s = "Löwe 老虎 Léopard";
907 /// let x: &[_] = &['1', '2'];
909 /// assert_eq!(s.find(x), None);
911 #[stable(feature = "rust1", since = "1.0.0")]
912 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
913 core_str::StrExt::find(self, pat)
916 /// Returns the byte index of the last character of this string slice that
917 /// matches the pattern.
919 /// Returns [`None`] if the pattern doesn't match.
921 /// The pattern can be a `&str`, [`char`], or a closure that determines if
922 /// a character matches.
924 /// [`char`]: primitive.char.html
925 /// [`None`]: option/enum.Option.html#variant.None
932 /// let s = "Löwe 老虎 Léopard";
934 /// assert_eq!(s.rfind('L'), Some(13));
935 /// assert_eq!(s.rfind('é'), Some(14));
938 /// More complex patterns with closures:
941 /// let s = "Löwe 老虎 Léopard";
943 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
944 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
947 /// Not finding the pattern:
950 /// let s = "Löwe 老虎 Léopard";
951 /// let x: &[_] = &['1', '2'];
953 /// assert_eq!(s.rfind(x), None);
955 #[stable(feature = "rust1", since = "1.0.0")]
956 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
957 where P::Searcher: ReverseSearcher<'a>
959 core_str::StrExt::rfind(self, pat)
962 /// An iterator over substrings of this string slice, separated by
963 /// characters matched by a pattern.
965 /// The pattern can be a `&str`, [`char`], or a closure that determines the
968 /// # Iterator behavior
970 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
971 /// allows a reverse search and forward/reverse search yields the same
972 /// elements. This is true for, eg, [`char`] but not for `&str`.
974 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
976 /// If the pattern allows a reverse search but its results might differ
977 /// from a forward search, the [`rsplit`] method can be used.
979 /// [`char`]: primitive.char.html
980 /// [`rsplit`]: #method.rsplit
987 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
988 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
990 /// let v: Vec<&str> = "".split('X').collect();
991 /// assert_eq!(v, [""]);
993 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
994 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
996 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
997 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
999 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1000 /// assert_eq!(v, ["abc", "def", "ghi"]);
1002 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1003 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1006 /// A more complex pattern, using a closure:
1009 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1010 /// assert_eq!(v, ["abc", "def", "ghi"]);
1013 /// If a string contains multiple contiguous separators, you will end up
1014 /// with empty strings in the output:
1017 /// let x = "||||a||b|c".to_string();
1018 /// let d: Vec<_> = x.split('|').collect();
1020 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1023 /// Contiguous separators are separated by the empty string.
1026 /// let x = "(///)".to_string();
1027 /// let d: Vec<_> = x.split('/').collect();;
1029 /// assert_eq!(d, &["(", "", "", ")"]);
1032 /// Separators at the start or end of a string are neighbored
1033 /// by empty strings.
1036 /// let d: Vec<_> = "010".split("0").collect();
1037 /// assert_eq!(d, &["", "1", ""]);
1040 /// When the empty string is used as a separator, it separates
1041 /// every character in the string, along with the beginning
1042 /// and end of the string.
1045 /// let f: Vec<_> = "rust".split("").collect();
1046 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1049 /// Contiguous separators can lead to possibly surprising behavior
1050 /// when whitespace is used as the separator. This code is correct:
1053 /// let x = " a b c".to_string();
1054 /// let d: Vec<_> = x.split(' ').collect();
1056 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1059 /// It does _not_ give you:
1062 /// assert_eq!(d, &["a", "b", "c"]);
1065 /// Use [`split_whitespace`] for this behavior.
1067 /// [`split_whitespace`]: #method.split_whitespace
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1070 core_str::StrExt::split(self, pat)
1073 /// An iterator over substrings of the given string slice, separated by
1074 /// characters matched by a pattern and yielded in reverse order.
1076 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1079 /// [`char`]: primitive.char.html
1081 /// # Iterator behavior
1083 /// The returned iterator requires that the pattern supports a reverse
1084 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1085 /// search yields the same elements.
1087 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1089 /// For iterating from the front, the [`split`] method can be used.
1091 /// [`split`]: #method.split
1095 /// Simple patterns:
1098 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1099 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1101 /// let v: Vec<&str> = "".rsplit('X').collect();
1102 /// assert_eq!(v, [""]);
1104 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1105 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1107 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1108 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1111 /// A more complex pattern, using a closure:
1114 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1115 /// assert_eq!(v, ["ghi", "def", "abc"]);
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1119 where P::Searcher: ReverseSearcher<'a>
1121 core_str::StrExt::rsplit(self, pat)
1124 /// An iterator over substrings of the given string slice, separated by
1125 /// characters matched by a pattern.
1127 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1130 /// Equivalent to [`split`], except that the trailing substring
1131 /// is skipped if empty.
1133 /// [`split`]: #method.split
1135 /// This method can be used for string data that is _terminated_,
1136 /// rather than _separated_ by a pattern.
1138 /// # Iterator behavior
1140 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1141 /// allows a reverse search and forward/reverse search yields the same
1142 /// elements. This is true for, eg, [`char`] but not for `&str`.
1144 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1145 /// [`char`]: primitive.char.html
1147 /// If the pattern allows a reverse search but its results might differ
1148 /// from a forward search, the [`rsplit_terminator`] method can be used.
1150 /// [`rsplit_terminator`]: #method.rsplit_terminator
1157 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1158 /// assert_eq!(v, ["A", "B"]);
1160 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1161 /// assert_eq!(v, ["A", "", "B", ""]);
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1165 core_str::StrExt::split_terminator(self, pat)
1168 /// An iterator over substrings of `self`, separated by characters
1169 /// matched by a pattern and yielded in reverse order.
1171 /// The pattern can be a simple `&str`, [`char`], or a closure that
1172 /// determines the split.
1173 /// Additional libraries might provide more complex patterns like
1174 /// regular expressions.
1176 /// [`char`]: primitive.char.html
1178 /// Equivalent to [`split`], except that the trailing substring is
1179 /// skipped if empty.
1181 /// [`split`]: #method.split
1183 /// This method can be used for string data that is _terminated_,
1184 /// rather than _separated_ by a pattern.
1186 /// # Iterator behavior
1188 /// The returned iterator requires that the pattern supports a
1189 /// reverse search, and it will be double ended if a forward/reverse
1190 /// search yields the same elements.
1192 /// For iterating from the front, the [`split_terminator`] method can be
1195 /// [`split_terminator`]: #method.split_terminator
1200 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1201 /// assert_eq!(v, ["B", "A"]);
1203 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1204 /// assert_eq!(v, ["", "B", "", "A"]);
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1208 where P::Searcher: ReverseSearcher<'a>
1210 core_str::StrExt::rsplit_terminator(self, pat)
1213 /// An iterator over substrings of the given string slice, separated by a
1214 /// pattern, restricted to returning at most `n` items.
1216 /// If `n` substrings are returned, the last substring (the `n`th substring)
1217 /// will contain the remainder of the string.
1219 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1222 /// [`char`]: primitive.char.html
1224 /// # Iterator behavior
1226 /// The returned iterator will not be double ended, because it is
1227 /// not efficient to support.
1229 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1232 /// [`rsplitn`]: #method.rsplitn
1236 /// Simple patterns:
1239 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1240 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1242 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1243 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1245 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1246 /// assert_eq!(v, ["abcXdef"]);
1248 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1249 /// assert_eq!(v, [""]);
1252 /// A more complex pattern, using a closure:
1255 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1256 /// assert_eq!(v, ["abc", "defXghi"]);
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1260 core_str::StrExt::splitn(self, n, pat)
1263 /// An iterator over substrings of this string slice, separated by a
1264 /// pattern, starting from the end of the string, restricted to returning
1265 /// at most `n` items.
1267 /// If `n` substrings are returned, the last substring (the `n`th substring)
1268 /// will contain the remainder of the string.
1270 /// The pattern can be a `&str`, [`char`], or a closure that
1271 /// determines the split.
1273 /// [`char`]: primitive.char.html
1275 /// # Iterator behavior
1277 /// The returned iterator will not be double ended, because it is not
1278 /// efficient to support.
1280 /// For splitting from the front, the [`splitn`] method can be used.
1282 /// [`splitn`]: #method.splitn
1286 /// Simple patterns:
1289 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1290 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1292 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1293 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1295 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1296 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1299 /// A more complex pattern, using a closure:
1302 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1303 /// assert_eq!(v, ["ghi", "abc1def"]);
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1307 where P::Searcher: ReverseSearcher<'a>
1309 core_str::StrExt::rsplitn(self, n, pat)
1312 /// An iterator over the matches of a pattern within the given string
1315 /// The pattern can be a `&str`, [`char`], or a closure that
1316 /// determines if a character matches.
1318 /// [`char`]: primitive.char.html
1320 /// # Iterator behavior
1322 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1323 /// allows a reverse search and forward/reverse search yields the same
1324 /// elements. This is true for, eg, [`char`] but not for `&str`.
1326 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1327 /// [`char`]: primitive.char.html
1329 /// If the pattern allows a reverse search but its results might differ
1330 /// from a forward search, the [`rmatches`] method can be used.
1332 /// [`rmatches`]: #method.rmatches
1339 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1340 /// assert_eq!(v, ["abc", "abc", "abc"]);
1342 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1343 /// assert_eq!(v, ["1", "2", "3"]);
1345 #[stable(feature = "str_matches", since = "1.2.0")]
1346 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1347 core_str::StrExt::matches(self, pat)
1350 /// An iterator over the matches of a pattern within this string slice,
1351 /// yielded in reverse order.
1353 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1354 /// a character matches.
1356 /// [`char`]: primitive.char.html
1358 /// # Iterator behavior
1360 /// The returned iterator requires that the pattern supports a reverse
1361 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1362 /// search yields the same elements.
1364 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1366 /// For iterating from the front, the [`matches`] method can be used.
1368 /// [`matches`]: #method.matches
1375 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1376 /// assert_eq!(v, ["abc", "abc", "abc"]);
1378 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1379 /// assert_eq!(v, ["3", "2", "1"]);
1381 #[stable(feature = "str_matches", since = "1.2.0")]
1382 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1383 where P::Searcher: ReverseSearcher<'a>
1385 core_str::StrExt::rmatches(self, pat)
1388 /// An iterator over the disjoint matches of a pattern within this string
1389 /// slice as well as the index that the match starts at.
1391 /// For matches of `pat` within `self` that overlap, only the indices
1392 /// corresponding to the first match are returned.
1394 /// The pattern can be a `&str`, [`char`], or a closure that determines
1395 /// 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
1407 /// If the pattern allows a reverse search but its results might differ
1408 /// from a forward search, the [`rmatch_indices`] method can be used.
1410 /// [`rmatch_indices`]: #method.rmatch_indices
1417 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1418 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1420 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1421 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1423 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1424 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1426 #[stable(feature = "str_match_indices", since = "1.5.0")]
1427 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1428 core_str::StrExt::match_indices(self, pat)
1431 /// An iterator over the disjoint matches of a pattern within `self`,
1432 /// yielded in reverse order along with the index of the match.
1434 /// For matches of `pat` within `self` that overlap, only the indices
1435 /// corresponding to the last match are returned.
1437 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1438 /// character matches.
1440 /// [`char`]: primitive.char.html
1442 /// # Iterator behavior
1444 /// The returned iterator requires that the pattern supports a reverse
1445 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1446 /// search yields the same elements.
1448 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1450 /// For iterating from the front, the [`match_indices`] method can be used.
1452 /// [`match_indices`]: #method.match_indices
1459 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1460 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1462 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1463 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1465 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1466 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1468 #[stable(feature = "str_match_indices", since = "1.5.0")]
1469 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1470 where P::Searcher: ReverseSearcher<'a>
1472 core_str::StrExt::rmatch_indices(self, pat)
1475 /// Returns a string slice with leading and trailing whitespace removed.
1477 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1478 /// Core Property `White_Space`.
1485 /// let s = " Hello\tworld\t";
1487 /// assert_eq!("Hello\tworld", s.trim());
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 pub fn trim(&self) -> &str {
1491 UnicodeStr::trim(self)
1494 /// Returns a string slice with leading whitespace removed.
1496 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1497 /// Core Property `White_Space`.
1499 /// # Text directionality
1501 /// A string is a sequence of bytes. 'Left' in this context means the first
1502 /// position of that byte string; for a language like Arabic or Hebrew
1503 /// which are 'right to left' rather than 'left to right', this will be
1504 /// the _right_ side, not the left.
1511 /// let s = " Hello\tworld\t";
1513 /// assert_eq!("Hello\tworld\t", s.trim_left());
1519 /// let s = " English";
1520 /// assert!(Some('E') == s.trim_left().chars().next());
1522 /// let s = " עברית";
1523 /// assert!(Some('ע') == s.trim_left().chars().next());
1525 #[stable(feature = "rust1", since = "1.0.0")]
1526 pub fn trim_left(&self) -> &str {
1527 UnicodeStr::trim_left(self)
1530 /// Returns a string slice with trailing whitespace removed.
1532 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1533 /// Core Property `White_Space`.
1535 /// # Text directionality
1537 /// A string is a sequence of bytes. 'Right' in this context means the last
1538 /// position of that byte string; for a language like Arabic or Hebrew
1539 /// which are 'right to left' rather than 'left to right', this will be
1540 /// the _left_ side, not the right.
1547 /// let s = " Hello\tworld\t";
1549 /// assert_eq!(" Hello\tworld", s.trim_right());
1555 /// let s = "English ";
1556 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1558 /// let s = "עברית ";
1559 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 pub fn trim_right(&self) -> &str {
1563 UnicodeStr::trim_right(self)
1566 /// Returns a string slice with all prefixes and suffixes that match a
1567 /// pattern repeatedly removed.
1569 /// The pattern can be a [`char`] or a closure that determines if a
1570 /// character matches.
1572 /// [`char`]: primitive.char.html
1576 /// Simple patterns:
1579 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1580 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1582 /// let x: &[_] = &['1', '2'];
1583 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1586 /// A more complex pattern, using a closure:
1589 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1593 where P::Searcher: DoubleEndedSearcher<'a>
1595 core_str::StrExt::trim_matches(self, pat)
1598 /// Returns a string slice with all prefixes that match a pattern
1599 /// repeatedly removed.
1601 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1602 /// a character matches.
1604 /// [`char`]: primitive.char.html
1606 /// # Text directionality
1608 /// A string is a sequence of bytes. 'Left' in this context means the first
1609 /// position of that byte string; for a language like Arabic or Hebrew
1610 /// which are 'right to left' rather than 'left to right', this will be
1611 /// the _right_ side, not the left.
1618 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1619 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1621 /// let x: &[_] = &['1', '2'];
1622 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1626 core_str::StrExt::trim_left_matches(self, pat)
1629 /// Returns a string slice with all suffixes that match a pattern
1630 /// repeatedly removed.
1632 /// The pattern can be a `&str`, [`char`], or a closure that
1633 /// determines if a character matches.
1635 /// [`char`]: primitive.char.html
1637 /// # Text directionality
1639 /// A string is a sequence of bytes. 'Right' in this context means the last
1640 /// position of that byte string; for a language like Arabic or Hebrew
1641 /// which are 'right to left' rather than 'left to right', this will be
1642 /// the _left_ side, not the right.
1646 /// Simple patterns:
1649 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1650 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1652 /// let x: &[_] = &['1', '2'];
1653 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1656 /// A more complex pattern, using a closure:
1659 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1663 where P::Searcher: ReverseSearcher<'a>
1665 core_str::StrExt::trim_right_matches(self, pat)
1668 /// Parses this string slice into another type.
1670 /// Because `parse` is so general, it can cause problems with type
1671 /// inference. As such, `parse` is one of the few times you'll see
1672 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1673 /// helps the inference algorithm understand specifically which type
1674 /// you're trying to parse into.
1676 /// `parse` can parse any type that implements the [`FromStr`] trait.
1678 /// [`FromStr`]: str/trait.FromStr.html
1682 /// Will return [`Err`] if it's not possible to parse this string slice into
1683 /// the desired type.
1685 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1692 /// let four: u32 = "4".parse().unwrap();
1694 /// assert_eq!(4, four);
1697 /// Using the 'turbofish' instead of annotating `four`:
1700 /// let four = "4".parse::<u32>();
1702 /// assert_eq!(Ok(4), four);
1705 /// Failing to parse:
1708 /// let nope = "j".parse::<u32>();
1710 /// assert!(nope.is_err());
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1715 core_str::StrExt::parse(self)
1718 /// Replaces all matches of a pattern with another string.
1720 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1721 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1722 /// replaces them with the replacement string slice.
1724 /// [`String`]: string/struct.String.html
1731 /// let s = "this is old";
1733 /// assert_eq!("this is new", s.replace("old", "new"));
1736 /// When the pattern doesn't match:
1739 /// let s = "this is old";
1740 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1744 let mut result = String::new();
1745 let mut last_end = 0;
1746 for (start, part) in self.match_indices(from) {
1747 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1748 result.push_str(to);
1749 last_end = start + part.len();
1751 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1755 /// Replaces first N matches of a pattern with another string.
1757 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1758 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1759 /// replaces them with the replacement string slice at most `count` times.
1761 /// [`String`]: string/struct.String.html
1768 /// let s = "foo foo 123 foo";
1769 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1770 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1771 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1774 /// When the pattern doesn't match:
1777 /// let s = "this is old";
1778 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1780 #[stable(feature = "str_replacen", since = "1.16.0")]
1781 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1782 // Hope to reduce the times of re-allocation
1783 let mut result = String::with_capacity(32);
1784 let mut last_end = 0;
1785 for (start, part) in self.match_indices(pat).take(count) {
1786 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1787 result.push_str(to);
1788 last_end = start + part.len();
1790 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1794 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1796 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1799 /// Since some characters can expand into multiple characters when changing
1800 /// the case, this function returns a [`String`] instead of modifying the
1801 /// parameter in-place.
1803 /// [`String`]: string/struct.String.html
1810 /// let s = "HELLO";
1812 /// assert_eq!("hello", s.to_lowercase());
1815 /// A tricky example, with sigma:
1818 /// let sigma = "Σ";
1820 /// assert_eq!("σ", sigma.to_lowercase());
1822 /// // but at the end of a word, it's ς, not σ:
1823 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1825 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1828 /// Languages without case are not changed:
1831 /// let new_year = "农历新年";
1833 /// assert_eq!(new_year, new_year.to_lowercase());
1835 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1836 pub fn to_lowercase(&self) -> String {
1837 let mut s = String::with_capacity(self.len());
1838 for (i, c) in self[..].char_indices() {
1840 // Σ maps to σ, except at the end of a word where it maps to ς.
1841 // This is the only conditional (contextual) but language-independent mapping
1842 // in `SpecialCasing.txt`,
1843 // so hard-code it rather than have a generic "condition" mechanism.
1844 // See https://github.com/rust-lang/rust/issues/26035
1845 map_uppercase_sigma(self, i, &mut s)
1847 s.extend(c.to_lowercase());
1852 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1853 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1854 // for the definition of `Final_Sigma`.
1855 debug_assert!('Σ'.len_utf8() == 2);
1856 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1857 !case_ignoreable_then_cased(from[i + 2..].chars());
1858 to.push_str(if is_word_final { "ς" } else { "σ" });
1861 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1862 use std_unicode::derived_property::{Cased, Case_Ignorable};
1863 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1864 Some(c) => Cased(c),
1870 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1872 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1875 /// Since some characters can expand into multiple characters when changing
1876 /// the case, this function returns a [`String`] instead of modifying the
1877 /// parameter in-place.
1879 /// [`String`]: string/struct.String.html
1886 /// let s = "hello";
1888 /// assert_eq!("HELLO", s.to_uppercase());
1891 /// Scripts without case are not changed:
1894 /// let new_year = "农历新年";
1896 /// assert_eq!(new_year, new_year.to_uppercase());
1898 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1899 pub fn to_uppercase(&self) -> String {
1900 let mut s = String::with_capacity(self.len());
1901 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1905 /// Escapes each char in `s` with [`char::escape_debug`].
1907 /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
1908 #[unstable(feature = "str_escape",
1909 reason = "return type may change to be an iterator",
1911 pub fn escape_debug(&self) -> String {
1912 self.chars().flat_map(|c| c.escape_debug()).collect()
1915 /// Escapes each char in `s` with [`char::escape_default`].
1917 /// [`char::escape_default`]: primitive.char.html#method.escape_default
1918 #[unstable(feature = "str_escape",
1919 reason = "return type may change to be an iterator",
1921 pub fn escape_default(&self) -> String {
1922 self.chars().flat_map(|c| c.escape_default()).collect()
1925 /// Escapes each char in `s` with [`char::escape_unicode`].
1927 /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
1928 #[unstable(feature = "str_escape",
1929 reason = "return type may change to be an iterator",
1931 pub fn escape_unicode(&self) -> String {
1932 self.chars().flat_map(|c| c.escape_unicode()).collect()
1935 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
1937 /// [`String`]: string/struct.String.html
1938 /// [`Box<str>`]: boxed/struct.Box.html
1945 /// let string = String::from("birthday gift");
1946 /// let boxed_str = string.clone().into_boxed_str();
1948 /// assert_eq!(boxed_str.into_string(), string);
1950 #[stable(feature = "box_str", since = "1.4.0")]
1951 pub fn into_string(self: Box<str>) -> String {
1953 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1954 String::from_utf8_unchecked(slice.into_vec())
1958 /// Create a [`String`] by repeating a string `n` times.
1960 /// [`String`]: string/struct.String.html
1967 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
1969 #[stable(feature = "repeat_str", since = "1.16.0")]
1970 pub fn repeat(&self, n: usize) -> String {
1971 let mut s = String::with_capacity(self.len() * n);
1972 s.extend((0..n).map(|_| self));