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 //! *[See also the `str` primitive type](../primitive.str.html).*
16 #![stable(feature = "rust1", since = "1.0.0")]
18 // Many of the usings in this module are only used in the test configuration.
19 // It's cleaner to just turn off the unused_imports warning than to fix them.
20 #![allow(unused_imports)]
22 use core::str as core_str;
23 use core::str::pattern::Pattern;
24 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
26 use rustc_unicode::str::{UnicodeStr, Utf16Encoder};
28 use vec_deque::VecDeque;
29 use borrow::{Borrow, ToOwned};
33 use slice::SliceConcatExt;
36 #[stable(feature = "rust1", since = "1.0.0")]
37 pub use core::str::{FromStr, Utf8Error};
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub use core::str::{Lines, LinesAny, CharRange};
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub use core::str::{Split, RSplit};
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub use core::str::{SplitN, RSplitN};
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub use core::str::{SplitTerminator, RSplitTerminator};
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub use core::str::{Matches, RMatches};
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub use core::str::{MatchIndices, RMatchIndices};
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub use core::str::{from_utf8_unchecked, ParseBoolError};
55 #[stable(feature = "rust1", since = "1.0.0")]
56 pub use rustc_unicode::str::SplitWhitespace;
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub use core::str::pattern;
60 #[unstable(feature = "slice_concat_ext",
61 reason = "trait should not have to exist",
63 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
66 fn concat(&self) -> String {
71 // `len` calculation may overflow but push_str will check boundaries
72 let len = self.iter().map(|s| s.borrow().len()).sum();
73 let mut result = String::with_capacity(len);
76 result.push_str(s.borrow())
82 fn join(&self, sep: &str) -> String {
92 // this is wrong without the guarantee that `self` is non-empty
93 // `len` calculation may overflow but push_str but will check boundaries
94 let len = sep.len() * (self.len() - 1) +
95 self.iter().map(|s| s.borrow().len()).sum::<usize>();
96 let mut result = String::with_capacity(len);
103 result.push_str(sep);
105 result.push_str(s.borrow());
110 fn connect(&self, sep: &str) -> String {
115 /// External iterator for a string's UTF-16 code units.
117 /// For use with the `std::iter` module.
119 #[unstable(feature = "str_utf16", issue = "27714")]
120 pub struct Utf16Units<'a> {
121 encoder: Utf16Encoder<Chars<'a>>,
124 #[stable(feature = "rust1", since = "1.0.0")]
125 impl<'a> Iterator for Utf16Units<'a> {
129 fn next(&mut self) -> Option<u16> {
134 fn size_hint(&self) -> (usize, Option<usize>) {
135 self.encoder.size_hint()
139 // Return the initial codepoint accumulator for the first byte.
140 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
141 // for width 3, and 3 bits for width 4
142 macro_rules! utf8_first_byte {
143 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
146 // return the value of $ch updated with continuation byte $byte
147 macro_rules! utf8_acc_cont_byte {
148 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
151 #[stable(feature = "rust1", since = "1.0.0")]
152 impl Borrow<str> for String {
154 fn borrow(&self) -> &str {
159 #[stable(feature = "rust1", since = "1.0.0")]
160 impl ToOwned for str {
162 fn to_owned(&self) -> String {
163 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
167 /// Methods for string slices.
171 /// Returns the length of `self`.
173 /// This length is in bytes, not [`char`]s or graphemes. In other words,
174 /// it may not be what a human considers the length of the string.
176 /// [`char`]: primitive.char.html
183 /// let len = "foo".len();
184 /// assert_eq!(3, len);
186 /// let len = "ƒoo".len(); // fancy f!
187 /// assert_eq!(4, len);
189 #[stable(feature = "rust1", since = "1.0.0")]
191 pub fn len(&self) -> usize {
192 core_str::StrExt::len(self)
195 /// Returns true if this slice has a length of zero bytes.
203 /// assert!(s.is_empty());
205 /// let s = "not empty";
206 /// assert!(!s.is_empty());
209 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn is_empty(&self) -> bool {
211 core_str::StrExt::is_empty(self)
214 /// Checks that `index`-th byte lies at the start and/or end of a
215 /// UTF-8 code point sequence.
217 /// The start and end of the string (when `index == self.len()`) are
221 /// Returns `false` if `index` is greater than `self.len()`.
226 /// #![feature(str_char)]
228 /// let s = "Löwe 老虎 Léopard";
229 /// assert!(s.is_char_boundary(0));
231 /// assert!(s.is_char_boundary(6));
232 /// assert!(s.is_char_boundary(s.len()));
234 /// // second byte of `ö`
235 /// assert!(!s.is_char_boundary(2));
237 /// // third byte of `老`
238 /// assert!(!s.is_char_boundary(8));
240 #[unstable(feature = "str_char",
241 reason = "it is unclear whether this method pulls its weight \
242 with the existence of the char_indices iterator or \
243 this method may want to be replaced with checked \
247 pub fn is_char_boundary(&self, index: usize) -> bool {
248 core_str::StrExt::is_char_boundary(self, index)
251 /// Converts a string slice to a byte slice.
258 /// let bytes = "bors".as_bytes();
259 /// assert_eq!(b"bors", bytes);
261 #[stable(feature = "rust1", since = "1.0.0")]
263 pub fn as_bytes(&self) -> &[u8] {
264 core_str::StrExt::as_bytes(self)
267 /// Converts a string slice to a raw pointer.
269 /// As string slices are a slice of bytes, the raw pointer points to a
270 /// [`u8`]. This pointer will be pointing to the first byte of the string
273 /// [`u8`]: primitive.u8.html
281 /// let ptr = s.as_ptr();
283 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn as_ptr(&self) -> *const u8 {
286 core_str::StrExt::as_ptr(self)
289 /// Creates a string slice from another string slice, bypassing safety
292 /// This new slice goes from `begin` to `end`, including `begin` but
295 /// To get a mutable string slice instead, see the
296 /// [`slice_mut_unchecked()`] method.
298 /// [`slice_mut_unchecked()`]: #method.slice_mut_unchecked
302 /// Callers of this function are responsible that three preconditions are
305 /// * `begin` must come before `end`.
306 /// * `begin` and `end` must be byte positions within the string slice.
307 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
314 /// let s = "Löwe 老虎 Léopard";
317 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
320 /// let s = "Hello, world!";
323 /// assert_eq!("world", s.slice_unchecked(7, 12));
326 #[stable(feature = "rust1", since = "1.0.0")]
328 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
329 core_str::StrExt::slice_unchecked(self, begin, end)
332 /// Creates a string slice from another string slice, bypassing safety
335 /// This new slice goes from `begin` to `end`, including `begin` but
338 /// To get an immutable string slice instead, see the
339 /// [`slice_unchecked()`] method.
341 /// [`slice_unchecked()`]: #method.slice_unchecked
345 /// Callers of this function are responsible that three preconditions are
348 /// * `begin` must come before `end`.
349 /// * `begin` and `end` must be byte positions within the string slice.
350 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
351 #[stable(feature = "str_slice_mut", since = "1.5.0")]
353 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
354 core_str::StrExt::slice_mut_unchecked(self, begin, end)
357 /// Given a byte position, returns the next `char` and its index.
361 /// If `i` is greater than or equal to the length of the string.
362 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
366 /// This example manually iterates through the code points of a string;
367 /// this should normally be
368 /// done by `.chars()` or `.char_indices()`.
371 /// #![feature(str_char)]
373 /// use std::str::CharRange;
375 /// let s = "中华Việt Nam";
377 /// while i < s.len() {
378 /// let CharRange {ch, next} = s.char_range_at(i);
379 /// println!("{}: {}", i, ch);
400 #[unstable(feature = "str_char",
401 reason = "often replaced by char_indices, this method may \
402 be removed in favor of just char_at() or eventually \
406 pub fn char_range_at(&self, start: usize) -> CharRange {
407 core_str::StrExt::char_range_at(self, start)
410 /// Given a byte position, returns the previous `char` and its position.
412 /// Note that Unicode has many features, such as combining marks, ligatures,
413 /// and direction marks, that need to be taken into account to correctly reverse a string.
415 /// Returns 0 for next index if called on start index 0.
419 /// If `i` is greater than the length of the string.
420 /// If `i` is not an index following a valid UTF-8 sequence.
424 /// This example manually iterates through the code points of a string;
425 /// this should normally be
426 /// done by `.chars().rev()` or `.char_indices()`.
429 /// #![feature(str_char)]
431 /// use std::str::CharRange;
433 /// let s = "中华Việt Nam";
434 /// let mut i = s.len();
436 /// let CharRange {ch, next} = s.char_range_at_reverse(i);
437 /// println!("{}: {}", i, ch);
458 #[unstable(feature = "str_char",
459 reason = "often replaced by char_indices, this method may \
460 be removed in favor of just char_at_reverse() or \
461 eventually removed altogether",
464 pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
465 core_str::StrExt::char_range_at_reverse(self, start)
468 /// Given a byte position, returns the `char` at that position.
472 /// If `i` is greater than or equal to the length of the string.
473 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
478 /// #![feature(str_char)]
481 /// assert_eq!(s.char_at(1), 'b');
482 /// assert_eq!(s.char_at(2), 'π');
483 /// assert_eq!(s.char_at(4), 'c');
485 #[unstable(feature = "str_char",
486 reason = "frequently replaced by the chars() iterator, this \
487 method may be removed or possibly renamed in the \
488 future; it is normally replaced by chars/char_indices \
489 iterators or by getting the first char from a \
493 pub fn char_at(&self, i: usize) -> char {
494 core_str::StrExt::char_at(self, i)
497 /// Given a byte position, returns the `char` at that position, counting
502 /// If `i` is greater than the length of the string.
503 /// If `i` is not an index following a valid UTF-8 sequence.
508 /// #![feature(str_char)]
511 /// assert_eq!(s.char_at_reverse(1), 'a');
512 /// assert_eq!(s.char_at_reverse(2), 'b');
513 /// assert_eq!(s.char_at_reverse(3), 'π');
515 #[unstable(feature = "str_char",
516 reason = "see char_at for more details, but reverse semantics \
517 are also somewhat unclear, especially with which \
518 cases generate panics",
521 pub fn char_at_reverse(&self, i: usize) -> char {
522 core_str::StrExt::char_at_reverse(self, i)
525 /// Retrieves the first `char` from a `&str` and returns it.
527 /// Note that a single Unicode character (grapheme cluster)
528 /// can be composed of multiple `char`s.
530 /// This does not allocate a new string; instead, it returns a slice that
531 /// points one code point beyond the code point that was shifted.
533 /// `None` is returned if the slice is empty.
538 /// #![feature(str_char)]
540 /// let s = "Łódź"; // \u{141}o\u{301}dz\u{301}
541 /// let (c, s1) = s.slice_shift_char().unwrap();
543 /// assert_eq!(c, 'Ł');
544 /// assert_eq!(s1, "ódź");
546 /// let (c, s2) = s1.slice_shift_char().unwrap();
548 /// assert_eq!(c, 'o');
549 /// assert_eq!(s2, "\u{301}dz\u{301}");
551 #[unstable(feature = "str_char",
552 reason = "awaiting conventions about shifting and slices and \
553 may not be warranted with the existence of the chars \
554 and/or char_indices iterators",
557 pub fn slice_shift_char(&self) -> Option<(char, &str)> {
558 core_str::StrExt::slice_shift_char(self)
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 s = "Per Martin-Löf";
621 /// let (first, last) = s.split_at(3);
623 /// assert_eq!("Per", first);
624 /// assert_eq!(" Martin-Löf", last);
627 #[stable(feature = "str_split_at", since = "1.4.0")]
628 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
629 core_str::StrExt::split_at_mut(self, mid)
632 /// Returns an iterator over the `char`s of a string slice.
634 /// As a string slice consists of valid UTF-8, we can iterate through a
635 /// string slice by [`char`]. This method returns such an iterator.
637 /// It's important to remember that [`char`] represents a Unicode Scalar
638 /// Value, and may not match your idea of what a 'character' is. Iteration
639 /// over grapheme clusters may be what you actually want.
641 /// [`char`]: primitive.char.html
648 /// let word = "goodbye";
650 /// let count = word.chars().count();
651 /// assert_eq!(7, count);
653 /// let mut chars = word.chars();
655 /// assert_eq!(Some('g'), chars.next());
656 /// assert_eq!(Some('o'), chars.next());
657 /// assert_eq!(Some('o'), chars.next());
658 /// assert_eq!(Some('d'), chars.next());
659 /// assert_eq!(Some('b'), chars.next());
660 /// assert_eq!(Some('y'), chars.next());
661 /// assert_eq!(Some('e'), chars.next());
663 /// assert_eq!(None, chars.next());
666 /// Remember, [`char`]s may not match your human intuition about characters:
671 /// let mut chars = y.chars();
673 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
674 /// assert_eq!(Some('\u{0306}'), chars.next());
676 /// assert_eq!(None, chars.next());
678 #[stable(feature = "rust1", since = "1.0.0")]
680 pub fn chars(&self) -> Chars {
681 core_str::StrExt::chars(self)
683 /// Returns an iterator over the [`char`]s of a string slice, and their
686 /// As a string slice consists of valid UTF-8, we can iterate through a
687 /// string slice by [`char`]. This method returns an iterator of both
688 /// these [`char`]s, as well as their byte positions.
690 /// The iterator yields tuples. The position is first, the [`char`] is
693 /// [`char`]: primitive.char.html
700 /// let word = "goodbye";
702 /// let count = word.char_indices().count();
703 /// assert_eq!(7, count);
705 /// let mut char_indices = word.char_indices();
707 /// assert_eq!(Some((0, 'g')), char_indices.next());
708 /// assert_eq!(Some((1, 'o')), char_indices.next());
709 /// assert_eq!(Some((2, 'o')), char_indices.next());
710 /// assert_eq!(Some((3, 'd')), char_indices.next());
711 /// assert_eq!(Some((4, 'b')), char_indices.next());
712 /// assert_eq!(Some((5, 'y')), char_indices.next());
713 /// assert_eq!(Some((6, 'e')), char_indices.next());
715 /// assert_eq!(None, char_indices.next());
718 /// Remember, [`char`]s may not match your human intuition about characters:
723 /// let mut char_indices = y.char_indices();
725 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
726 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
728 /// assert_eq!(None, char_indices.next());
730 #[stable(feature = "rust1", since = "1.0.0")]
732 pub fn char_indices(&self) -> CharIndices {
733 core_str::StrExt::char_indices(self)
736 /// An iterator over the bytes of a string slice.
738 /// As a string slice consists of a sequence of bytes, we can iterate
739 /// through a string slice by byte. This method returns such an iterator.
746 /// let mut bytes = "bors".bytes();
748 /// assert_eq!(Some(b'b'), bytes.next());
749 /// assert_eq!(Some(b'o'), bytes.next());
750 /// assert_eq!(Some(b'r'), bytes.next());
751 /// assert_eq!(Some(b's'), bytes.next());
753 /// assert_eq!(None, bytes.next());
755 #[stable(feature = "rust1", since = "1.0.0")]
757 pub fn bytes(&self) -> Bytes {
758 core_str::StrExt::bytes(self)
761 /// Split a string slice by whitespace.
763 /// The iterator returned will return string slices that are sub-slices of
764 /// the original string slice, separated by any amount of whitespace.
766 /// 'Whitespace' is defined according to the terms of the Unicode Derived
767 /// Core Property `White_Space`.
774 /// let mut iter = "A few words".split_whitespace();
776 /// assert_eq!(Some("A"), iter.next());
777 /// assert_eq!(Some("few"), iter.next());
778 /// assert_eq!(Some("words"), iter.next());
780 /// assert_eq!(None, iter.next());
783 /// All kinds of whitespace are considered:
786 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
787 /// assert_eq!(Some("Mary"), iter.next());
788 /// assert_eq!(Some("had"), iter.next());
789 /// assert_eq!(Some("a"), iter.next());
790 /// assert_eq!(Some("little"), iter.next());
791 /// assert_eq!(Some("lamb"), iter.next());
793 /// assert_eq!(None, iter.next());
795 #[stable(feature = "split_whitespace", since = "1.1.0")]
797 pub fn split_whitespace(&self) -> SplitWhitespace {
798 UnicodeStr::split_whitespace(self)
801 /// An iterator over the lines of a string, as string slices.
803 /// Lines are ended with either a newline (`\n`) or a carriage return with
804 /// a line feed (`\r\n`).
806 /// The final line ending is optional.
813 /// let text = "foo\r\nbar\n\nbaz\n";
814 /// let mut lines = text.lines();
816 /// assert_eq!(Some("foo"), lines.next());
817 /// assert_eq!(Some("bar"), lines.next());
818 /// assert_eq!(Some(""), lines.next());
819 /// assert_eq!(Some("baz"), lines.next());
821 /// assert_eq!(None, lines.next());
824 /// The final line ending isn't required:
827 /// let text = "foo\nbar\n\r\nbaz";
828 /// let mut lines = text.lines();
830 /// assert_eq!(Some("foo"), lines.next());
831 /// assert_eq!(Some("bar"), lines.next());
832 /// assert_eq!(Some(""), lines.next());
833 /// assert_eq!(Some("baz"), lines.next());
835 /// assert_eq!(None, lines.next());
837 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn lines(&self) -> Lines {
840 core_str::StrExt::lines(self)
843 /// An iterator over the lines of a string.
844 #[stable(feature = "rust1", since = "1.0.0")]
845 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
848 pub fn lines_any(&self) -> LinesAny {
849 core_str::StrExt::lines_any(self)
852 /// Returns an iterator of `u16` over the string encoded as UTF-16.
853 #[unstable(feature = "str_utf16",
854 reason = "this functionality may only be provided by libunicode",
856 pub fn utf16_units(&self) -> Utf16Units {
857 Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
860 /// Returns `true` if the given pattern matches a sub-slice of
861 /// this string slice.
863 /// Returns `false` if it does not.
870 /// let bananas = "bananas";
872 /// assert!(bananas.contains("nana"));
873 /// assert!(!bananas.contains("apples"));
875 #[stable(feature = "rust1", since = "1.0.0")]
876 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
877 core_str::StrExt::contains(self, pat)
880 /// Returns `true` if the given pattern matches a prefix of this
883 /// Returns `false` if it does not.
890 /// let bananas = "bananas";
892 /// assert!(bananas.starts_with("bana"));
893 /// assert!(!bananas.starts_with("nana"));
895 #[stable(feature = "rust1", since = "1.0.0")]
896 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
897 core_str::StrExt::starts_with(self, pat)
900 /// Returns `true` if the given pattern matches a suffix of this
903 /// Returns `false` if it does not.
910 /// let bananas = "bananas";
912 /// assert!(bananas.ends_with("anas"));
913 /// assert!(!bananas.ends_with("nana"));
915 #[stable(feature = "rust1", since = "1.0.0")]
916 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
917 where P::Searcher: ReverseSearcher<'a>
919 core_str::StrExt::ends_with(self, pat)
922 /// Returns the byte index of the first character of this string slice that
923 /// matches the pattern.
925 /// Returns [`None`] if the pattern doesn't match.
927 /// The pattern can be a `&str`, [`char`], or a closure that determines if
928 /// a character matches.
930 /// [`char`]: primitive.char.html
931 /// [`None`]: option/enum.Option.html#variant.None
938 /// let s = "Löwe 老虎 Léopard";
940 /// assert_eq!(s.find('L'), Some(0));
941 /// assert_eq!(s.find('é'), Some(14));
942 /// assert_eq!(s.find("Léopard"), Some(13));
945 /// More complex patterns with closures:
948 /// let s = "Löwe 老虎 Léopard";
950 /// assert_eq!(s.find(char::is_whitespace), Some(5));
951 /// assert_eq!(s.find(char::is_lowercase), Some(1));
954 /// Not finding the pattern:
957 /// let s = "Löwe 老虎 Léopard";
958 /// let x: &[_] = &['1', '2'];
960 /// assert_eq!(s.find(x), None);
962 #[stable(feature = "rust1", since = "1.0.0")]
963 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
964 core_str::StrExt::find(self, pat)
967 /// Returns the byte index of the last character of this string slice that
968 /// matches the pattern.
970 /// Returns [`None`] if the pattern doesn't match.
972 /// The pattern can be a `&str`, [`char`], or a closure that determines if
973 /// a character matches.
975 /// [`char`]: primitive.char.html
976 /// [`None`]: option/enum.Option.html#variant.None
983 /// let s = "Löwe 老虎 Léopard";
985 /// assert_eq!(s.rfind('L'), Some(13));
986 /// assert_eq!(s.rfind('é'), Some(14));
989 /// More complex patterns with closures:
992 /// let s = "Löwe 老虎 Léopard";
994 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
995 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
998 /// Not finding the pattern:
1001 /// let s = "Löwe 老虎 Léopard";
1002 /// let x: &[_] = &['1', '2'];
1004 /// assert_eq!(s.rfind(x), None);
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1008 where P::Searcher: ReverseSearcher<'a>
1010 core_str::StrExt::rfind(self, pat)
1013 /// An iterator over substrings of this string slice, separated by
1014 /// characters matched by a pattern.
1016 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1019 /// # Iterator behavior
1021 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1022 /// allows a reverse search and forward/reverse search yields the same
1023 /// elements. This is true for, eg, [`char`] but not for `&str`.
1025 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1027 /// If the pattern allows a reverse search but its results might differ
1028 /// from a forward search, the [`rsplit()`] method can be used.
1030 /// [`char`]: primitive.char.html
1031 /// [`rsplit()`]: #method.rsplit
1035 /// Simple patterns:
1038 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1039 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1041 /// let v: Vec<&str> = "".split('X').collect();
1042 /// assert_eq!(v, [""]);
1044 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1045 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1047 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1048 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1050 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1051 /// assert_eq!(v, ["abc", "def", "ghi"]);
1053 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1054 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1057 /// A more complex pattern, using a closure:
1060 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1061 /// assert_eq!(v, ["abc", "def", "ghi"]);
1064 /// If a string contains multiple contiguous separators, you will end up
1065 /// with empty strings in the output:
1068 /// let x = "||||a||b|c".to_string();
1069 /// let d: Vec<_> = x.split('|').collect();
1071 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1074 /// This can lead to possibly surprising behavior when whitespace is used
1075 /// as the separator. This code is correct:
1078 /// let x = " a b c".to_string();
1079 /// let d: Vec<_> = x.split(' ').collect();
1081 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1084 /// It does _not_ give you:
1087 /// assert_eq!(d, &["a", "b", "c"]);
1090 /// Use [`split_whitespace()`] for this behavior.
1092 /// [`split_whitespace()`]: #method.split_whitespace
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1095 core_str::StrExt::split(self, pat)
1098 /// An iterator over substrings of the given string slice, separated by
1099 /// characters matched by a pattern and yielded in reverse order.
1101 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1104 /// [`char`]: primitive.char.html
1106 /// # Iterator behavior
1108 /// The returned iterator requires that the pattern supports a reverse
1109 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1110 /// search yields the same elements.
1112 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1114 /// For iterating from the front, the [`split()`] method can be used.
1116 /// [`split()`]: #method.split
1120 /// Simple patterns:
1123 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1124 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1126 /// let v: Vec<&str> = "".rsplit('X').collect();
1127 /// assert_eq!(v, [""]);
1129 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1130 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1132 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1133 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1136 /// A more complex pattern, using a closure:
1139 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1140 /// assert_eq!(v, ["ghi", "def", "abc"]);
1142 #[stable(feature = "rust1", since = "1.0.0")]
1143 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1144 where P::Searcher: ReverseSearcher<'a>
1146 core_str::StrExt::rsplit(self, pat)
1149 /// An iterator over substrings of the given string slice, separated by
1150 /// characters matched by a pattern.
1152 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1155 /// Equivalent to [`split()`], except that the trailing substring
1156 /// is skipped if empty.
1158 /// [`split()`]: #method.split
1160 /// This method can be used for string data that is _terminated_,
1161 /// rather than _separated_ by a pattern.
1163 /// # Iterator behavior
1165 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1166 /// allows a reverse search and forward/reverse search yields the same
1167 /// elements. This is true for, eg, [`char`] but not for `&str`.
1169 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1170 /// [`char`]: primitive.char.html
1172 /// If the pattern allows a reverse search but its results might differ
1173 /// from a forward search, the [`rsplit_terminator()`] method can be used.
1175 /// [`rsplit_terminator()`]: #method.rsplit_terminator
1182 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1183 /// assert_eq!(v, ["A", "B"]);
1185 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1186 /// assert_eq!(v, ["A", "", "B", ""]);
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1190 core_str::StrExt::split_terminator(self, pat)
1193 /// An iterator over substrings of `self`, separated by characters
1194 /// matched by a pattern and yielded in reverse order.
1196 /// The pattern can be a simple `&str`, [`char`], or a closure that
1197 /// determines the split.
1198 /// Additional libraries might provide more complex patterns like
1199 /// regular expressions.
1201 /// [`char`]: primitive.char.html
1203 /// Equivalent to [`split()`], except that the trailing substring is
1204 /// skipped if empty.
1206 /// [`split()`]: #method.split
1208 /// This method can be used for string data that is _terminated_,
1209 /// rather than _separated_ by a pattern.
1211 /// # Iterator behavior
1213 /// The returned iterator requires that the pattern supports a
1214 /// reverse search, and it will be double ended if a forward/reverse
1215 /// search yields the same elements.
1217 /// For iterating from the front, the [`split_terminator()`] method can be
1220 /// [`split_terminator()`]: #method.split_terminator
1225 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1226 /// assert_eq!(v, ["B", "A"]);
1228 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1229 /// assert_eq!(v, ["", "B", "", "A"]);
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1233 where P::Searcher: ReverseSearcher<'a>
1235 core_str::StrExt::rsplit_terminator(self, pat)
1238 /// An iterator over substrings of the given string slice, separated by a
1239 /// pattern, restricted to returning at most `count` items.
1241 /// The last element returned, if any, will contain the remainder of the
1244 /// The pattern can be a `&str`, [`char`], or a closure that determines the
1247 /// [`char`]: primitive.char.html
1249 /// # Iterator behavior
1251 /// The returned iterator will not be double ended, because it is
1252 /// not efficient to support.
1254 /// If the pattern allows a reverse search, the [`rsplitn()`] method can be
1257 /// [`rsplitn()`]: #method.rsplitn
1261 /// Simple patterns:
1264 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1265 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1267 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1268 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1270 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1271 /// assert_eq!(v, ["abcXdef"]);
1273 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1274 /// assert_eq!(v, [""]);
1277 /// A more complex pattern, using a closure:
1280 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1281 /// assert_eq!(v, ["abc", "defXghi"]);
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 pub fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1285 core_str::StrExt::splitn(self, count, pat)
1288 /// An iterator over substrings of this string slice, separated by a
1289 /// pattern, starting from the end of the string, restricted to returning
1290 /// at most `count` items.
1292 /// The last element returned, if any, will contain the remainder of the
1295 /// The pattern can be a `&str`, [`char`], or a closure that
1296 /// determines the split.
1298 /// [`char`]: primitive.char.html
1300 /// # Iterator behavior
1302 /// The returned iterator will not be double ended, because it is not
1303 /// efficient to support.
1305 /// For splitting from the front, the [`splitn()`] method can be used.
1307 /// [`splitn()`]: #method.splitn
1311 /// Simple patterns:
1314 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1315 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1317 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1318 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1320 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1321 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1324 /// A more complex pattern, using a closure:
1327 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1328 /// assert_eq!(v, ["ghi", "abc1def"]);
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1332 where P::Searcher: ReverseSearcher<'a>
1334 core_str::StrExt::rsplitn(self, count, pat)
1337 /// An iterator over the matches of a pattern within the given string
1340 /// The pattern can be a `&str`, [`char`], or a closure that
1341 /// determines if a character matches.
1343 /// [`char`]: primitive.char.html
1345 /// # Iterator behavior
1347 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1348 /// allows a reverse search and forward/reverse search yields the same
1349 /// elements. This is true for, eg, [`char`] but not for `&str`.
1351 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1352 /// [`char`]: primitive.char.html
1354 /// If the pattern allows a reverse search but its results might differ
1355 /// from a forward search, the [`rmatches()`] method can be used.
1357 /// [`rmatches()`]: #method.rmatches
1364 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1365 /// assert_eq!(v, ["abc", "abc", "abc"]);
1367 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1368 /// assert_eq!(v, ["1", "2", "3"]);
1370 #[stable(feature = "str_matches", since = "1.2.0")]
1371 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1372 core_str::StrExt::matches(self, pat)
1375 /// An iterator over the matches of a pattern within this string slice,
1376 /// yielded in reverse order.
1378 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1379 /// a character matches.
1381 /// [`char`]: primitive.char.html
1383 /// # Iterator behavior
1385 /// The returned iterator requires that the pattern supports a reverse
1386 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1387 /// search yields the same elements.
1389 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1391 /// For iterating from the front, the [`matches()`] method can be used.
1393 /// [`matches()`]: #method.matches
1400 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1401 /// assert_eq!(v, ["abc", "abc", "abc"]);
1403 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1404 /// assert_eq!(v, ["3", "2", "1"]);
1406 #[stable(feature = "str_matches", since = "1.2.0")]
1407 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1408 where P::Searcher: ReverseSearcher<'a>
1410 core_str::StrExt::rmatches(self, pat)
1413 /// An iterator over the disjoint matches of a pattern within this string
1414 /// slice as well as the index that the match starts at.
1416 /// For matches of `pat` within `self` that overlap, only the indices
1417 /// corresponding to the first match are returned.
1419 /// The pattern can be a `&str`, [`char`], or a closure that determines
1420 /// if a character matches.
1422 /// [`char`]: primitive.char.html
1424 /// # Iterator behavior
1426 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1427 /// allows a reverse search and forward/reverse search yields the same
1428 /// elements. This is true for, eg, [`char`] but not for `&str`.
1430 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1432 /// If the pattern allows a reverse search but its results might differ
1433 /// from a forward search, the [`rmatch_indices()`] method can be used.
1435 /// [`rmatch_indices()`]: #method.rmatch_indices
1442 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1443 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1445 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1446 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1448 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1449 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1451 #[stable(feature = "str_match_indices", since = "1.5.0")]
1452 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1453 core_str::StrExt::match_indices(self, pat)
1456 /// An iterator over the disjoint matches of a pattern within `self`,
1457 /// yielded in reverse order along with the index of the match.
1459 /// For matches of `pat` within `self` that overlap, only the indices
1460 /// corresponding to the last match are returned.
1462 /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1463 /// character matches.
1465 /// [`char`]: primitive.char.html
1467 /// # Iterator behavior
1469 /// The returned iterator requires that the pattern supports a reverse
1470 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1471 /// search yields the same elements.
1473 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1475 /// For iterating from the front, the [`match_indices()`] method can be used.
1477 /// [`match_indices()`]: #method.match_indices
1484 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1485 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1487 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1488 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1490 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1491 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1493 #[stable(feature = "str_match_indices", since = "1.5.0")]
1494 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1495 where P::Searcher: ReverseSearcher<'a>
1497 core_str::StrExt::rmatch_indices(self, pat)
1500 /// Returns a string slice with leading and trailing whitespace removed.
1502 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1503 /// Core Property `White_Space`.
1510 /// let s = " Hello\tworld\t";
1512 /// assert_eq!("Hello\tworld", s.trim());
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 pub fn trim(&self) -> &str {
1516 UnicodeStr::trim(self)
1519 /// Returns a string slice with leading whitespace removed.
1521 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1522 /// Core Property `White_Space`.
1524 /// # Text directionality
1526 /// A string is a sequence of bytes. 'Left' in this context means the first
1527 /// position of that byte string; for a language like Arabic or Hebrew
1528 /// which are 'right to left' rather than 'left to right', this will be
1529 /// the _right_ side, not the left.
1536 /// let s = " Hello\tworld\t";
1538 /// assert_eq!("Hello\tworld\t", s.trim_left());
1544 /// let s = " English";
1545 /// assert!(Some('E') == s.trim_left().chars().next());
1547 /// let s = " עברית";
1548 /// assert!(Some('ע') == s.trim_left().chars().next());
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 pub fn trim_left(&self) -> &str {
1552 UnicodeStr::trim_left(self)
1555 /// Returns a string slice with trailing whitespace removed.
1557 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1558 /// Core Property `White_Space`.
1560 /// # Text directionality
1562 /// A string is a sequence of bytes. 'Right' in this context means the last
1563 /// position of that byte string; for a language like Arabic or Hebrew
1564 /// which are 'right to left' rather than 'left to right', this will be
1565 /// the _left_ side, not the right.
1572 /// let s = " Hello\tworld\t";
1574 /// assert_eq!(" Hello\tworld", s.trim_right());
1580 /// let s = "English ";
1581 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1583 /// let s = "עברית ";
1584 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1586 #[stable(feature = "rust1", since = "1.0.0")]
1587 pub fn trim_right(&self) -> &str {
1588 UnicodeStr::trim_right(self)
1591 /// Returns a string slice with all prefixes and suffixes that match a
1592 /// pattern repeatedly removed.
1594 /// The pattern can be a `&str`, [`char`], or a closure that determines
1595 /// if a character matches.
1597 /// [`char`]: primitive.char.html
1601 /// Simple patterns:
1604 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1605 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1607 /// let x: &[_] = &['1', '2'];
1608 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1611 /// A more complex pattern, using a closure:
1614 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1618 where P::Searcher: DoubleEndedSearcher<'a>
1620 core_str::StrExt::trim_matches(self, pat)
1623 /// Returns a string slice with all prefixes that match a pattern
1624 /// repeatedly removed.
1626 /// The pattern can be a `&str`, [`char`], or a closure that determines if
1627 /// a character matches.
1629 /// [`char`]: primitive.char.html
1631 /// # Text directionality
1633 /// A string is a sequence of bytes. 'Left' in this context means the first
1634 /// position of that byte string; for a language like Arabic or Hebrew
1635 /// which are 'right to left' rather than 'left to right', this will be
1636 /// the _right_ side, not the left.
1643 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1644 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1646 /// let x: &[_] = &['1', '2'];
1647 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1649 #[stable(feature = "rust1", since = "1.0.0")]
1650 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1651 core_str::StrExt::trim_left_matches(self, pat)
1654 /// Returns a string slice with all suffixes that match a pattern
1655 /// repeatedly removed.
1657 /// The pattern can be a `&str`, [`char`], or a closure that
1658 /// determines if a character matches.
1660 /// [`char`]: primitive.char.html
1662 /// # Text directionality
1664 /// A string is a sequence of bytes. 'Right' in this context means the last
1665 /// position of that byte string; for a language like Arabic or Hebrew
1666 /// which are 'right to left' rather than 'left to right', this will be
1667 /// the _left_ side, not the right.
1671 /// Simple patterns:
1674 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1675 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1677 /// let x: &[_] = &['1', '2'];
1678 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1681 /// A more complex pattern, using a closure:
1684 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1686 #[stable(feature = "rust1", since = "1.0.0")]
1687 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1688 where P::Searcher: ReverseSearcher<'a>
1690 core_str::StrExt::trim_right_matches(self, pat)
1693 /// Parses this string slice into another type.
1695 /// Because `parse()` is so general, it can cause problems with type
1696 /// inference. As such, `parse()` is one of the few times you'll see
1697 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1698 /// helps the inference algorithm understand specifically which type
1699 /// you're trying to parse into.
1701 /// `parse()` can parse any type that implements the [`FromStr`] trait.
1703 /// [`FromStr`]: str/trait.FromStr.html
1707 /// Will return [`Err`] if it's not possible to parse this string slice into
1708 /// the desired type.
1710 /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1717 /// let four: u32 = "4".parse().unwrap();
1719 /// assert_eq!(4, four);
1722 /// Using the 'turbofish' instead of annotating `four`:
1725 /// let four = "4".parse::<u32>();
1727 /// assert_eq!(Ok(4), four);
1730 /// Failing to parse:
1733 /// let nope = "j".parse::<u32>();
1735 /// assert!(nope.is_err());
1738 #[stable(feature = "rust1", since = "1.0.0")]
1739 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1740 core_str::StrExt::parse(self)
1743 /// Replaces all matches of a pattern with another string.
1745 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1746 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1747 /// replaces them with the replacement string slice.
1749 /// [`String`]: string/struct.String.html
1756 /// let s = "this is old";
1758 /// assert_eq!("this is new", s.replace("old", "new"));
1761 /// When the pattern doesn't match:
1764 /// let s = "this is old";
1765 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1767 #[stable(feature = "rust1", since = "1.0.0")]
1768 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1769 let mut result = String::new();
1770 let mut last_end = 0;
1771 for (start, part) in self.match_indices(from) {
1772 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1773 result.push_str(to);
1774 last_end = start + part.len();
1776 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1780 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1782 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1785 /// [`String`]: string/struct.String.html
1792 /// let s = "HELLO";
1794 /// assert_eq!("hello", s.to_lowercase());
1797 /// A tricky example, with sigma:
1800 /// let sigma = "Σ";
1802 /// assert_eq!("σ", sigma.to_lowercase());
1804 /// // but at the end of a word, it's ς, not σ:
1805 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1807 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1810 /// Languages without case are not changed:
1813 /// let new_year = "农历新年";
1815 /// assert_eq!(new_year, new_year.to_lowercase());
1817 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1818 pub fn to_lowercase(&self) -> String {
1819 let mut s = String::with_capacity(self.len());
1820 for (i, c) in self[..].char_indices() {
1822 // Σ maps to σ, except at the end of a word where it maps to ς.
1823 // This is the only conditional (contextual) but language-independent mapping
1824 // in `SpecialCasing.txt`,
1825 // so hard-code it rather than have a generic "condition" mechanism.
1826 // See https://github.com/rust-lang/rust/issues/26035
1827 map_uppercase_sigma(self, i, &mut s)
1829 s.extend(c.to_lowercase());
1834 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1835 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1836 // for the definition of `Final_Sigma`.
1837 debug_assert!('Σ'.len_utf8() == 2);
1838 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1839 !case_ignoreable_then_cased(from[i + 2..].chars());
1840 to.push_str(if is_word_final {
1847 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1848 use rustc_unicode::derived_property::{Cased, Case_Ignorable};
1849 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1850 Some(c) => Cased(c),
1856 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1858 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1861 /// [`String`]: string/struct.String.html
1868 /// let s = "hello";
1870 /// assert_eq!("HELLO", s.to_uppercase());
1873 /// Scripts without case are not changed:
1876 /// let new_year = "农历新年";
1878 /// assert_eq!(new_year, new_year.to_uppercase());
1880 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1881 pub fn to_uppercase(&self) -> String {
1882 let mut s = String::with_capacity(self.len());
1883 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1887 /// Escapes each char in `s` with `char::escape_default`.
1888 #[unstable(feature = "str_escape",
1889 reason = "return type may change to be an iterator",
1891 pub fn escape_default(&self) -> String {
1892 self.chars().flat_map(|c| c.escape_default()).collect()
1895 /// Escapes each char in `s` with `char::escape_unicode`.
1896 #[unstable(feature = "str_escape",
1897 reason = "return type may change to be an iterator",
1899 pub fn escape_unicode(&self) -> String {
1900 self.chars().flat_map(|c| c.escape_unicode()).collect()
1903 /// Converts a `Box<str>` into a [`String`] without copying or allocating.
1905 /// [`String`]: string/struct.String.html
1912 /// let string = String::from("birthday gift");
1913 /// let boxed_str = string.clone().into_boxed_str();
1915 /// assert_eq!(boxed_str.into_string(), string);
1917 #[stable(feature = "box_str", since = "1.4.0")]
1918 pub fn into_string(self: Box<str>) -> String {
1920 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1921 String::from_utf8_unchecked(slice.into_vec())