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::clone::Clone;
23 use core::iter::{Iterator, Extend};
24 use core::option::Option::{self, Some, None};
25 use core::result::Result;
26 use core::str as core_str;
27 use core::str::pattern::Pattern;
28 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
30 use rustc_unicode::str::{UnicodeStr, Utf16Encoder};
32 use vec_deque::VecDeque;
33 use borrow::{Borrow, ToOwned};
37 use slice::SliceConcatExt;
40 pub use core::str::{FromStr, Utf8Error};
41 pub use core::str::{Lines, LinesAny, CharRange};
42 pub use core::str::{Split, RSplit};
43 pub use core::str::{SplitN, RSplitN};
44 pub use core::str::{SplitTerminator, RSplitTerminator};
45 pub use core::str::{Matches, RMatches};
46 pub use core::str::{MatchIndices, RMatchIndices};
47 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
48 pub use core::str::{from_utf8_unchecked, ParseBoolError};
49 pub use rustc_unicode::str::{SplitWhitespace};
50 pub use core::str::pattern;
52 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
55 fn concat(&self) -> String {
60 // `len` calculation may overflow but push_str will check boundaries
61 let len = self.iter().map(|s| s.borrow().len()).sum();
62 let mut result = String::with_capacity(len);
65 result.push_str(s.borrow())
71 fn join(&self, sep: &str) -> String {
81 // this is wrong without the guarantee that `self` is non-empty
82 // `len` calculation may overflow but push_str but will check boundaries
83 let len = sep.len() * (self.len() - 1)
84 + self.iter().map(|s| s.borrow().len()).sum::<usize>();
85 let mut result = String::with_capacity(len);
94 result.push_str(s.borrow());
99 fn connect(&self, sep: &str) -> String {
104 /// External iterator for a string's UTF16 codeunits.
106 /// For use with the `std::iter` module.
108 #[unstable(feature = "str_utf16", issue = "27714")]
109 pub struct Utf16Units<'a> {
110 encoder: Utf16Encoder<Chars<'a>>
113 #[stable(feature = "rust1", since = "1.0.0")]
114 impl<'a> Iterator for Utf16Units<'a> {
118 fn next(&mut self) -> Option<u16> { self.encoder.next() }
121 fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
124 // Return the initial codepoint accumulator for the first byte.
125 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
126 // for width 3, and 3 bits for width 4
127 macro_rules! utf8_first_byte {
128 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
131 // return the value of $ch updated with continuation byte $byte
132 macro_rules! utf8_acc_cont_byte {
133 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
136 #[stable(feature = "rust1", since = "1.0.0")]
137 impl Borrow<str> for String {
139 fn borrow(&self) -> &str { &self[..] }
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl ToOwned for str {
145 fn to_owned(&self) -> String {
147 String::from_utf8_unchecked(self.as_bytes().to_owned())
152 /// Any string that can be represented as a slice.
155 #[stable(feature = "rust1", since = "1.0.0")]
157 /// Returns the length of `self` in bytes.
162 /// assert_eq!("foo".len(), 3);
163 /// assert_eq!("ƒoo".len(), 4); // fancy f!
165 #[stable(feature = "rust1", since = "1.0.0")]
167 pub fn len(&self) -> usize {
168 core_str::StrExt::len(self)
171 /// Returns true if this slice has a length of zero bytes.
176 /// assert!("".is_empty());
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub fn is_empty(&self) -> bool {
181 core_str::StrExt::is_empty(self)
184 /// Checks that `index`-th byte lies at the start and/or end of a
185 /// UTF-8 code point sequence.
187 /// The start and end of the string (when `index == self.len()`) are
191 /// Returns `false` if `index` is greater than `self.len()`.
196 /// #![feature(str_char)]
198 /// let s = "Löwe 老虎 Léopard";
199 /// assert!(s.is_char_boundary(0));
201 /// assert!(s.is_char_boundary(6));
202 /// assert!(s.is_char_boundary(s.len()));
204 /// // second byte of `ö`
205 /// assert!(!s.is_char_boundary(2));
207 /// // third byte of `老`
208 /// assert!(!s.is_char_boundary(8));
210 #[unstable(feature = "str_char",
211 reason = "it is unclear whether this method pulls its weight \
212 with the existence of the char_indices iterator or \
213 this method may want to be replaced with checked \
217 pub fn is_char_boundary(&self, index: usize) -> bool {
218 core_str::StrExt::is_char_boundary(self, index)
221 /// Converts `self` to a byte slice.
226 /// assert_eq!("bors".as_bytes(), b"bors");
228 #[stable(feature = "rust1", since = "1.0.0")]
230 pub fn as_bytes(&self) -> &[u8] {
231 core_str::StrExt::as_bytes(self)
234 /// Returns a raw pointer to the `&str`'s buffer.
236 /// The caller must ensure that the string outlives this pointer, and
238 /// reallocated (e.g. by pushing to the string).
244 /// let p = s.as_ptr();
246 #[stable(feature = "rust1", since = "1.0.0")]
248 pub fn as_ptr(&self) -> *const u8 {
249 core_str::StrExt::as_ptr(self)
252 /// Takes a bytewise slice from a string.
254 /// Returns the substring from [`begin`..`end`).
258 /// Caller must check both UTF-8 sequence boundaries and the boundaries
259 /// of the entire slice as well.
264 /// let s = "Löwe 老虎 Léopard";
267 /// assert_eq!(s.slice_unchecked(0, 21), "Löwe 老虎 Léopard");
270 #[stable(feature = "rust1", since = "1.0.0")]
272 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
273 core_str::StrExt::slice_unchecked(self, begin, end)
276 /// Takes a bytewise mutable slice from a string.
278 /// Same as `slice_unchecked`, but works with `&mut str` instead of `&str`.
279 #[unstable(feature = "str_slice_mut", reason = "recently added",
282 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
283 core_str::StrExt::slice_mut_unchecked(self, begin, end)
286 /// Given a byte position, return the next code point and its index.
288 /// This can be used to iterate over the Unicode code points of a string.
292 /// If `i` is greater than or equal to the length of the string.
293 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
297 /// This example manually iterates through the code points of a string;
298 /// this should normally be
299 /// done by `.chars()` or `.char_indices()`.
302 /// #![feature(str_char, core)]
304 /// use std::str::CharRange;
306 /// let s = "中华Việt Nam";
308 /// while i < s.len() {
309 /// let CharRange {ch, next} = s.char_range_at(i);
310 /// println!("{}: {}", i, ch);
331 #[unstable(feature = "str_char",
332 reason = "often replaced by char_indices, this method may \
333 be removed in favor of just char_at() or eventually \
337 pub fn char_range_at(&self, start: usize) -> CharRange {
338 core_str::StrExt::char_range_at(self, start)
341 /// Given a byte position, return the previous `char` and its position.
343 /// This function can be used to iterate over a Unicode code points in reverse.
345 /// Note that Unicode has many features, such as combining marks, ligatures,
346 /// and direction marks, that need to be taken into account to correctly reverse a string.
348 /// Returns 0 for next index if called on start index 0.
352 /// If `i` is greater than the length of the string.
353 /// If `i` is not an index following a valid UTF-8 sequence.
357 /// This example manually iterates through the code points of a string;
358 /// this should normally be
359 /// done by `.chars().rev()` or `.char_indices()`.
362 /// #![feature(str_char, core)]
364 /// use std::str::CharRange;
366 /// let s = "中华Việt Nam";
367 /// let mut i = s.len();
369 /// let CharRange {ch, next} = s.char_range_at_reverse(i);
370 /// println!("{}: {}", i, ch);
391 #[unstable(feature = "str_char",
392 reason = "often replaced by char_indices, this method may \
393 be removed in favor of just char_at_reverse() or \
394 eventually removed altogether",
397 pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
398 core_str::StrExt::char_range_at_reverse(self, start)
401 /// Given a byte position, return the `char` at that position.
405 /// If `i` is greater than or equal to the length of the string.
406 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
411 /// #![feature(str_char)]
414 /// assert_eq!(s.char_at(1), 'b');
415 /// assert_eq!(s.char_at(2), 'π');
416 /// assert_eq!(s.char_at(4), 'c');
418 #[unstable(feature = "str_char",
419 reason = "frequently replaced by the chars() iterator, this \
420 method may be removed or possibly renamed in the \
421 future; it is normally replaced by chars/char_indices \
422 iterators or by getting the first char from a \
426 pub fn char_at(&self, i: usize) -> char {
427 core_str::StrExt::char_at(self, i)
430 /// Given a byte position, return the `char` at that position, counting
435 /// If `i` is greater than the length of the string.
436 /// If `i` is not an index following a valid UTF-8 sequence.
441 /// #![feature(str_char)]
444 /// assert_eq!(s.char_at_reverse(1), 'a');
445 /// assert_eq!(s.char_at_reverse(2), 'b');
446 /// assert_eq!(s.char_at_reverse(3), 'π');
448 #[unstable(feature = "str_char",
449 reason = "see char_at for more details, but reverse semantics \
450 are also somewhat unclear, especially with which \
451 cases generate panics",
454 pub fn char_at_reverse(&self, i: usize) -> char {
455 core_str::StrExt::char_at_reverse(self, i)
458 /// Retrieves the first code point from a `&str` and returns it.
460 /// Note that a single Unicode character (grapheme cluster)
461 /// can be composed of multiple `char`s.
463 /// This does not allocate a new string; instead, it returns a slice that
464 /// points one code point beyond the code point that was shifted.
466 /// `None` is returned if the slice is empty.
471 /// #![feature(str_char)]
473 /// let s = "Łódź"; // \u{141}o\u{301}dz\u{301}
474 /// let (c, s1) = s.slice_shift_char().unwrap();
476 /// assert_eq!(c, 'Ł');
477 /// assert_eq!(s1, "ódź");
479 /// let (c, s2) = s1.slice_shift_char().unwrap();
481 /// assert_eq!(c, 'o');
482 /// assert_eq!(s2, "\u{301}dz\u{301}");
484 #[unstable(feature = "str_char",
485 reason = "awaiting conventions about shifting and slices and \
486 may not be warranted with the existence of the chars \
487 and/or char_indices iterators",
490 pub fn slice_shift_char(&self) -> Option<(char, &str)> {
491 core_str::StrExt::slice_shift_char(self)
494 /// Divide one string slice into two at an index.
496 /// The index `mid` is a byte offset from the start of the string
497 /// that must be on a `char` boundary.
499 /// Return slices `&self[..mid]` and `&self[mid..]`.
503 /// Panics if `mid` is beyond the last code point of the string,
504 /// or if it is not on a `char` boundary.
508 /// #![feature(str_split_at)]
510 /// let s = "Löwe 老虎 Léopard";
511 /// let first_space = s.find(' ').unwrap_or(s.len());
512 /// let (a, b) = s.split_at(first_space);
514 /// assert_eq!(a, "Löwe");
515 /// assert_eq!(b, " 老虎 Léopard");
518 #[unstable(feature = "str_split_at", reason = "recently added",
520 pub fn split_at(&self, mid: usize) -> (&str, &str) {
521 core_str::StrExt::split_at(self, mid)
524 /// Divide one mutable string slice into two at an index.
526 #[unstable(feature = "str_split_at", reason = "recently added",
528 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
529 core_str::StrExt::split_at_mut(self, mid)
532 /// An iterator over the code points of `self`.
534 /// In Unicode relationship between code points and characters is complex.
535 /// A single character may be composed of multiple code points
536 /// (e.g. diacritical marks added to a letter), and a single code point
537 /// (e.g. Hangul syllable) may contain multiple characters.
539 /// For iteration over human-readable characters a grapheme cluster iterator
540 /// may be more appropriate. See the [unicode-segmentation crate][1].
542 /// [1]: https://crates.io/crates/unicode-segmentation
547 /// let v: Vec<char> = "ASCII żółć 🇨🇭 한".chars().collect();
549 /// assert_eq!(v, ['A', 'S', 'C', 'I', 'I', ' ',
550 /// 'z', '\u{307}', 'o', '\u{301}', 'ł', 'c', '\u{301}', ' ',
551 /// '\u{1f1e8}', '\u{1f1ed}', ' ', '한']);
553 #[stable(feature = "rust1", since = "1.0.0")]
555 pub fn chars(&self) -> Chars {
556 core_str::StrExt::chars(self)
559 /// An iterator over the `char`s of `self` and their byte offsets.
564 /// let v: Vec<(usize, char)> = "A🇨🇭".char_indices().collect();
565 /// let b = vec![(0, 'A'), (1, '\u{1f1e8}'), (5, '\u{1f1ed}')];
567 /// assert_eq!(v, b);
569 #[stable(feature = "rust1", since = "1.0.0")]
571 pub fn char_indices(&self) -> CharIndices {
572 core_str::StrExt::char_indices(self)
575 /// An iterator over the bytes of `self`.
580 /// let v: Vec<u8> = "bors".bytes().collect();
582 /// assert_eq!(v, b"bors".to_vec());
584 #[stable(feature = "rust1", since = "1.0.0")]
586 pub fn bytes(&self) -> Bytes {
587 core_str::StrExt::bytes(self)
590 /// An iterator over the non-empty substrings of `self` which contain no whitespace,
591 /// and which are separated by any amount of whitespace.
596 /// let some_words = " Mary had\ta\u{2009}little \n\t lamb";
597 /// let v: Vec<&str> = some_words.split_whitespace().collect();
599 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
601 #[stable(feature = "split_whitespace", since = "1.1.0")]
603 pub fn split_whitespace(&self) -> SplitWhitespace {
604 UnicodeStr::split_whitespace(self)
607 /// An iterator over the lines of a string, separated by `\n` or `\r\n`.
609 /// This does not include the empty string after a trailing newline or CRLF.
614 /// let four_lines = "foo\nbar\n\r\nbaz";
615 /// let v: Vec<&str> = four_lines.lines().collect();
617 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
620 /// Leaving off the trailing character:
623 /// let four_lines = "foo\r\nbar\n\nbaz\n";
624 /// let v: Vec<&str> = four_lines.lines().collect();
626 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
628 #[stable(feature = "rust1", since = "1.0.0")]
630 pub fn lines(&self) -> Lines {
631 core_str::StrExt::lines(self)
634 /// An iterator over the lines of a string, separated by either
637 /// As with `.lines()`, this does not include an empty trailing line.
642 /// let four_lines = "foo\r\nbar\n\r\nbaz";
643 /// let v: Vec<&str> = four_lines.lines_any().collect();
645 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
648 /// Leaving off the trailing character:
651 /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
652 /// let v: Vec<&str> = four_lines.lines_any().collect();
654 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
656 #[stable(feature = "rust1", since = "1.0.0")]
657 #[deprecated(since = "1.4.0", reason = "use lines() instead now")]
660 pub fn lines_any(&self) -> LinesAny {
661 core_str::StrExt::lines_any(self)
664 /// Returns an iterator of `u16` over the string encoded as UTF-16.
665 #[unstable(feature = "str_utf16",
666 reason = "this functionality may only be provided by libunicode",
668 pub fn utf16_units(&self) -> Utf16Units {
669 Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
672 /// Returns `true` if `self` contains another `&str`.
677 /// assert!("bananas".contains("nana"));
679 /// assert!(!"bananas".contains("foobar"));
681 #[stable(feature = "rust1", since = "1.0.0")]
682 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
683 core_str::StrExt::contains(self, pat)
686 /// Returns `true` if the given `&str` is a prefix of the string.
691 /// assert!("banana".starts_with("ba"));
693 #[stable(feature = "rust1", since = "1.0.0")]
694 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
695 core_str::StrExt::starts_with(self, pat)
698 /// Returns true if the given `&str` is a suffix of the string.
703 /// assert!("banana".ends_with("nana"));
705 #[stable(feature = "rust1", since = "1.0.0")]
706 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
707 where P::Searcher: ReverseSearcher<'a>
709 core_str::StrExt::ends_with(self, pat)
712 /// Returns the byte index of the first character of `self` that matches
713 /// the pattern, if it
716 /// Returns `None` if it doesn't exist.
718 /// The pattern can be a simple `&str`, `char`, or a closure that
727 /// let s = "Löwe 老虎 Léopard";
729 /// assert_eq!(s.find('L'), Some(0));
730 /// assert_eq!(s.find('é'), Some(14));
731 /// assert_eq!(s.find("Léopard"), Some(13));
735 /// More complex patterns with closures:
738 /// let s = "Löwe 老虎 Léopard";
740 /// assert_eq!(s.find(char::is_whitespace), Some(5));
741 /// assert_eq!(s.find(char::is_lowercase), Some(1));
744 /// Not finding the pattern:
747 /// let s = "Löwe 老虎 Léopard";
748 /// let x: &[_] = &['1', '2'];
750 /// assert_eq!(s.find(x), None);
752 #[stable(feature = "rust1", since = "1.0.0")]
753 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
754 core_str::StrExt::find(self, pat)
757 /// Returns the byte index of the last character of `self` that
758 /// matches the pattern, if it
761 /// Returns `None` if it doesn't exist.
763 /// The pattern can be a simple `&str`, `char`,
764 /// or a closure that determines the split.
771 /// let s = "Löwe 老虎 Léopard";
773 /// assert_eq!(s.rfind('L'), Some(13));
774 /// assert_eq!(s.rfind('é'), Some(14));
777 /// More complex patterns with closures:
780 /// let s = "Löwe 老虎 Léopard";
782 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
783 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
786 /// Not finding the pattern:
789 /// let s = "Löwe 老虎 Léopard";
790 /// let x: &[_] = &['1', '2'];
792 /// assert_eq!(s.rfind(x), None);
794 #[stable(feature = "rust1", since = "1.0.0")]
795 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
796 where P::Searcher: ReverseSearcher<'a>
798 core_str::StrExt::rfind(self, pat)
801 /// An iterator over substrings of `self`, separated by characters
802 /// matched by a pattern.
804 /// The pattern can be a simple `&str`, `char`, or a closure that
805 /// determines the split. Additional libraries might provide more complex
806 /// patterns like regular expressions.
808 /// # Iterator behavior
810 /// The returned iterator will be double ended if the pattern allows a
811 /// reverse search and forward/reverse search yields the same elements.
812 /// This is true for, eg, `char` but not
815 /// If the pattern allows a reverse search but its results might differ
816 /// from a forward search, `rsplit()` can be used.
823 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
824 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
826 /// let v: Vec<&str> = "".split('X').collect();
827 /// assert_eq!(v, [""]);
829 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
830 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
832 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
833 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
835 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
836 /// assert_eq!(v, ["abc", "def", "ghi"]);
838 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
839 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
842 /// A more complex pattern, using a closure:
845 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
846 /// assert_eq!(v, ["abc", "def", "ghi"]);
849 /// If a string contains multiple contiguous separators, you will end up
850 /// with empty strings in the output:
853 /// let x = "||||a||b|c".to_string();
854 /// let d: Vec<_> = x.split('|').collect();
856 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
859 /// This can lead to possibly surprising behavior when whitespace is used
860 /// as the separator. This code is correct:
863 /// let x = " a b c".to_string();
864 /// let d: Vec<_> = x.split(' ').collect();
866 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
869 /// It does _not_ give you:
872 /// assert_eq!(d, &["a", "b", "c"]);
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
876 core_str::StrExt::split(self, pat)
879 /// An iterator over substrings of `self`, separated by characters
880 /// matched by a pattern and yielded in reverse order.
882 /// The pattern can be a simple `&str`, `char`, or a closure that
883 /// determines the split.
884 /// Additional libraries might provide more complex patterns like
885 /// regular expressions.
887 /// # Iterator behavior
889 /// The returned iterator requires that the pattern supports a
891 /// and it will be double ended if a forward/reverse search yields
892 /// the same elements.
894 /// For iterating from the front, `split()` can be used.
901 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
902 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
904 /// let v: Vec<&str> = "".rsplit('X').collect();
905 /// assert_eq!(v, [""]);
907 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
908 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
910 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
911 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
914 /// A more complex pattern, using a closure:
917 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
918 /// assert_eq!(v, ["ghi", "def", "abc"]);
920 #[stable(feature = "rust1", since = "1.0.0")]
921 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
922 where P::Searcher: ReverseSearcher<'a>
924 core_str::StrExt::rsplit(self, pat)
927 /// An iterator over substrings of `self`, separated by characters
928 /// matched by a pattern.
930 /// The pattern can be a simple `&str`, `char`, or a closure that
931 /// determines the split.
932 /// Additional libraries might provide more complex patterns
933 /// like regular expressions.
935 /// Equivalent to `split`, except that the trailing substring
936 /// is skipped if empty.
938 /// This method can be used for string data that is _terminated_,
939 /// rather than _separated_ by a pattern.
941 /// # Iterator behavior
943 /// The returned iterator will be double ended if the pattern allows a
945 /// and forward/reverse search yields the same elements. This is true
946 /// for, eg, `char` but not for `&str`.
948 /// If the pattern allows a reverse search but its results might differ
949 /// from a forward search, `rsplit_terminator()` can be used.
954 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
955 /// assert_eq!(v, ["A", "B"]);
957 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
958 /// assert_eq!(v, ["A", "", "B", ""]);
960 #[stable(feature = "rust1", since = "1.0.0")]
961 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
962 core_str::StrExt::split_terminator(self, pat)
965 /// An iterator over substrings of `self`, separated by characters
966 /// matched by a pattern and yielded in reverse order.
968 /// The pattern can be a simple `&str`, `char`, or a closure that
969 /// determines the split.
970 /// Additional libraries might provide more complex patterns like
971 /// regular expressions.
973 /// Equivalent to `split`, except that the trailing substring is
974 /// skipped if empty.
976 /// This method can be used for string data that is _terminated_,
977 /// rather than _separated_ by a pattern.
979 /// # Iterator behavior
981 /// The returned iterator requires that the pattern supports a
982 /// reverse search, and it will be double ended if a forward/reverse
983 /// search yields the same elements.
985 /// For iterating from the front, `split_terminator()` can be used.
990 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
991 /// assert_eq!(v, ["B", "A"]);
993 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
994 /// assert_eq!(v, ["", "B", "", "A"]);
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
998 where P::Searcher: ReverseSearcher<'a>
1000 core_str::StrExt::rsplit_terminator(self, pat)
1003 /// An iterator over substrings of `self`, separated by a pattern,
1004 /// restricted to returning
1005 /// at most `count` items.
1007 /// The last element returned, if any, will contain the remainder of the
1009 /// The pattern can be a simple `&str`, `char`, or a closure that
1010 /// determines the split.
1011 /// Additional libraries might provide more complex patterns like
1012 /// regular expressions.
1014 /// # Iterator behavior
1016 /// The returned iterator will not be double ended, because it is
1017 /// not efficient to support.
1019 /// If the pattern allows a reverse search, `rsplitn()` can be used.
1023 /// Simple patterns:
1026 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1027 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1029 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1030 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1032 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1033 /// assert_eq!(v, ["abcXdef"]);
1035 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1036 /// assert_eq!(v, [""]);
1039 /// A more complex pattern, using a closure:
1042 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1043 /// assert_eq!(v, ["abc", "defXghi"]);
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 pub fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1047 core_str::StrExt::splitn(self, count, pat)
1050 /// An iterator over substrings of `self`, separated by a pattern,
1051 /// starting from the end of the string, restricted to returning
1052 /// at most `count` items.
1054 /// The last element returned, if any, will contain the remainder of the
1057 /// The pattern can be a simple `&str`, `char`, or a closure that
1058 /// determines the split.
1059 /// Additional libraries might provide more complex patterns like
1060 /// regular expressions.
1062 /// # Iterator behavior
1064 /// The returned iterator will not be double ended, because it is not
1065 /// efficient to support.
1067 /// `splitn()` can be used for splitting from the front.
1071 /// Simple patterns:
1074 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1075 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1077 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1078 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1080 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1081 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1084 /// A more complex pattern, using a closure:
1087 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1088 /// assert_eq!(v, ["ghi", "abc1def"]);
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1092 where P::Searcher: ReverseSearcher<'a>
1094 core_str::StrExt::rsplitn(self, count, pat)
1097 /// An iterator over the matches of a pattern within `self`.
1099 /// The pattern can be a simple `&str`, `char`, or a closure that
1100 /// determines the split.
1101 /// Additional libraries might provide more complex patterns like
1102 /// regular expressions.
1104 /// # Iterator behavior
1106 /// The returned iterator will be double ended if the pattern allows
1107 /// a reverse search
1108 /// and forward/reverse search yields the same elements. This is true
1109 /// for, eg, `char` but not
1112 /// If the pattern allows a reverse search but its results might differ
1113 /// from a forward search, `rmatches()` can be used.
1118 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1119 /// assert_eq!(v, ["abc", "abc", "abc"]);
1121 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1122 /// assert_eq!(v, ["1", "2", "3"]);
1124 #[stable(feature = "str_matches", since = "1.2.0")]
1125 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1126 core_str::StrExt::matches(self, pat)
1129 /// An iterator over the matches of a pattern within `self`, yielded in
1132 /// The pattern can be a simple `&str`, `char`, or a closure that
1133 /// determines the split.
1134 /// Additional libraries might provide more complex patterns like
1135 /// regular expressions.
1137 /// # Iterator behavior
1139 /// The returned iterator requires that the pattern supports a
1141 /// and it will be double ended if a forward/reverse search yields
1142 /// the same elements.
1144 /// For iterating from the front, `matches()` can be used.
1149 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1150 /// assert_eq!(v, ["abc", "abc", "abc"]);
1152 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1153 /// assert_eq!(v, ["3", "2", "1"]);
1155 #[stable(feature = "str_matches", since = "1.2.0")]
1156 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1157 where P::Searcher: ReverseSearcher<'a>
1159 core_str::StrExt::rmatches(self, pat)
1162 /// An iterator over the start and end indices of the disjoint matches
1163 /// of a pattern within `self`.
1165 /// For matches of `pat` within `self` that overlap, only the indices
1166 /// corresponding to the first
1167 /// match are returned.
1169 /// The pattern can be a simple `&str`, `char`, or a closure that
1172 /// Additional libraries might provide more complex patterns like
1173 /// regular expressions.
1175 /// # Iterator behavior
1177 /// The returned iterator will be double ended if the pattern allows a
1179 /// and forward/reverse search yields the same elements. This is true for,
1180 /// eg, `char` but not
1183 /// If the pattern allows a reverse search but its results might differ
1184 /// from a forward search, `rmatch_indices()` can be used.
1189 /// #![feature(str_match_indices)]
1191 /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
1192 /// assert_eq!(v, [(0, 3), (6, 9), (12, 15)]);
1194 /// let v: Vec<(usize, usize)> = "1abcabc2".match_indices("abc").collect();
1195 /// assert_eq!(v, [(1, 4), (4, 7)]);
1197 /// let v: Vec<(usize, usize)> = "ababa".match_indices("aba").collect();
1198 /// assert_eq!(v, [(0, 3)]); // only the first `aba`
1200 #[unstable(feature = "str_match_indices",
1201 reason = "might have its iterator type changed",
1203 // NB: Right now MatchIndices yields `(usize, usize)`, but it would
1204 // be more consistent with `matches` and `char_indices` to return `(usize, &str)`
1205 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1206 core_str::StrExt::match_indices(self, pat)
1209 /// An iterator over the start and end indices of the disjoint matches of
1210 /// a pattern within
1211 /// `self`, yielded in reverse order.
1213 /// For matches of `pat` within `self` that overlap, only the indices
1214 /// corresponding to the last
1215 /// match are returned.
1217 /// The pattern can be a simple `&str`, `char`, or a closure that
1220 /// Additional libraries might provide more complex patterns like
1221 /// regular expressions.
1223 /// # Iterator behavior
1225 /// The returned iterator requires that the pattern supports a
1227 /// and it will be double ended if a forward/reverse search yields
1228 /// the same elements.
1230 /// For iterating from the front, `match_indices()` can be used.
1235 /// #![feature(str_match_indices)]
1237 /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1238 /// assert_eq!(v, [(12, 15), (6, 9), (0, 3)]);
1240 /// let v: Vec<(usize, usize)> = "1abcabc2".rmatch_indices("abc").collect();
1241 /// assert_eq!(v, [(4, 7), (1, 4)]);
1243 /// let v: Vec<(usize, usize)> = "ababa".rmatch_indices("aba").collect();
1244 /// assert_eq!(v, [(2, 5)]); // only the last `aba`
1246 #[unstable(feature = "str_match_indices",
1247 reason = "might have its iterator type changed",
1249 // NB: Right now RMatchIndices yields `(usize, usize)`, but it would
1250 // be more consistent with `rmatches` and `char_indices` to return `(usize, &str)`
1251 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1252 where P::Searcher: ReverseSearcher<'a>
1254 core_str::StrExt::rmatch_indices(self, pat)
1257 /// Returns a `&str` with leading and trailing whitespace removed.
1262 /// let s = " Hello\tworld\t";
1263 /// assert_eq!(s.trim(), "Hello\tworld");
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 pub fn trim(&self) -> &str {
1267 UnicodeStr::trim(self)
1270 /// Returns a `&str` with leading whitespace removed.
1275 /// let s = " Hello\tworld\t";
1276 /// assert_eq!(s.trim_left(), "Hello\tworld\t");
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 pub fn trim_left(&self) -> &str {
1280 UnicodeStr::trim_left(self)
1283 /// Returns a `&str` with trailing whitespace removed.
1288 /// let s = " Hello\tworld\t";
1289 /// assert_eq!(s.trim_right(), " Hello\tworld");
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 pub fn trim_right(&self) -> &str {
1293 UnicodeStr::trim_right(self)
1296 /// Returns a string with all pre- and suffixes that match a pattern
1297 /// repeatedly removed.
1299 /// The pattern can be a simple `char`, or a closure that determines
1304 /// Simple patterns:
1307 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1308 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1310 /// let x: &[_] = &['1', '2'];
1311 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1314 /// A more complex pattern, using a closure:
1317 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1321 where P::Searcher: DoubleEndedSearcher<'a>
1323 core_str::StrExt::trim_matches(self, pat)
1326 /// Returns a string with all prefixes that match a pattern
1327 /// repeatedly removed.
1329 /// The pattern can be a simple `&str`, `char`, or a closure that
1330 /// determines the split.
1335 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1336 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1338 /// let x: &[_] = &['1', '2'];
1339 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1343 core_str::StrExt::trim_left_matches(self, pat)
1346 /// Returns a string with all suffixes that match a pattern
1347 /// repeatedly removed.
1349 /// The pattern can be a simple `&str`, `char`, or a closure that
1350 /// determines the split.
1354 /// Simple patterns:
1357 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1358 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1360 /// let x: &[_] = &['1', '2'];
1361 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1364 /// A more complex pattern, using a closure:
1367 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1371 where P::Searcher: ReverseSearcher<'a>
1373 core_str::StrExt::trim_right_matches(self, pat)
1376 /// Parses `self` into the specified type.
1380 /// Will return `Err` if it's not possible to parse `self` into the type.
1385 /// assert_eq!("4".parse::<u32>(), Ok(4));
1391 /// assert!("j".parse::<u32>().is_err());
1394 #[stable(feature = "rust1", since = "1.0.0")]
1395 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1396 core_str::StrExt::parse(self)
1399 /// Replaces all occurrences of one string with another.
1401 /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a
1402 /// second `&str` to
1403 /// replace it with. If the original `&str` isn't found, no change occurs.
1408 /// let s = "this is old";
1410 /// assert_eq!(s.replace("old", "new"), "this is new");
1413 /// When a `&str` isn't found:
1416 /// let s = "this is old";
1417 /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 pub fn replace(&self, from: &str, to: &str) -> String {
1421 let mut result = String::new();
1422 let mut last_end = 0;
1423 for (start, end) in self.match_indices(from) {
1424 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1425 result.push_str(to);
1428 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1432 /// Returns the lowercase equivalent of this string.
1437 /// let s = "HELLO";
1438 /// assert_eq!(s.to_lowercase(), "hello");
1440 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1441 pub fn to_lowercase(&self) -> String {
1442 let mut s = String::with_capacity(self.len());
1443 for (i, c) in self[..].char_indices() {
1445 // Σ maps to σ, except at the end of a word where it maps to ς.
1446 // This is the only conditional (contextual) but language-independent mapping
1447 // in `SpecialCasing.txt`,
1448 // so hard-code it rather than have a generic "condition" mechanim.
1449 // See https://github.com/rust-lang/rust/issues/26035
1450 map_uppercase_sigma(self, i, &mut s)
1452 s.extend(c.to_lowercase());
1457 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1458 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1459 // for the definition of `Final_Sigma`.
1460 debug_assert!('Σ'.len_utf8() == 2);
1462 case_ignoreable_then_cased(from[..i].chars().rev()) &&
1463 !case_ignoreable_then_cased(from[i + 2..].chars());
1464 to.push_str(if is_word_final { "ς" } else { "σ" });
1467 fn case_ignoreable_then_cased<I: Iterator<Item=char>>(iter: I) -> bool {
1468 use rustc_unicode::derived_property::{Cased, Case_Ignorable};
1469 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1470 Some(c) => Cased(c),
1476 /// Returns the uppercase equivalent of this string.
1481 /// let s = "hello";
1482 /// assert_eq!(s.to_uppercase(), "HELLO");
1484 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1485 pub fn to_uppercase(&self) -> String {
1486 let mut s = String::with_capacity(self.len());
1487 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1491 /// Escapes each char in `s` with `char::escape_default`.
1492 #[unstable(feature = "str_escape",
1493 reason = "return type may change to be an iterator",
1495 pub fn escape_default(&self) -> String {
1496 self.chars().flat_map(|c| c.escape_default()).collect()
1499 /// Escapes each char in `s` with `char::escape_unicode`.
1500 #[unstable(feature = "str_escape",
1501 reason = "return type may change to be an iterator",
1503 pub fn escape_unicode(&self) -> String {
1504 self.chars().flat_map(|c| c.escape_unicode()).collect()
1507 /// Converts the `Box<str>` into a `String` without copying or allocating.
1508 #[unstable(feature = "box_str",
1509 reason = "recently added, matches RFC",
1511 pub fn into_string(self: Box<str>) -> String {
1513 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1514 String::from_utf8_unchecked(slice.into_vec())