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};
42 pub use core::str::{Lines, LinesAny, CharRange};
43 pub use core::str::{Split, RSplit};
44 pub use core::str::{SplitN, RSplitN};
45 pub use core::str::{SplitTerminator, RSplitTerminator};
46 pub use core::str::{Matches, RMatches};
47 pub use core::str::{MatchIndices, RMatchIndices};
48 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
49 pub use core::str::{from_utf8_unchecked, ParseBoolError};
50 pub use rustc_unicode::str::{SplitWhitespace};
51 pub use core::str::pattern;
53 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
56 fn concat(&self) -> String {
61 // `len` calculation may overflow but push_str will check boundaries
62 let len = self.iter().map(|s| s.borrow().len()).sum();
63 let mut result = String::with_capacity(len);
66 result.push_str(s.borrow())
72 fn join(&self, sep: &str) -> String {
82 // this is wrong without the guarantee that `self` is non-empty
83 // `len` calculation may overflow but push_str but will check boundaries
84 let len = sep.len() * (self.len() - 1)
85 + self.iter().map(|s| s.borrow().len()).sum::<usize>();
86 let mut result = String::with_capacity(len);
95 result.push_str(s.borrow());
100 fn connect(&self, sep: &str) -> String {
105 /// External iterator for a string's UTF-16 code units.
107 /// For use with the `std::iter` module.
109 #[unstable(feature = "str_utf16", issue = "27714")]
110 pub struct Utf16Units<'a> {
111 encoder: Utf16Encoder<Chars<'a>>
114 #[stable(feature = "rust1", since = "1.0.0")]
115 impl<'a> Iterator for Utf16Units<'a> {
119 fn next(&mut self) -> Option<u16> { self.encoder.next() }
122 fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
125 // Return the initial codepoint accumulator for the first byte.
126 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
127 // for width 3, and 3 bits for width 4
128 macro_rules! utf8_first_byte {
129 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
132 // return the value of $ch updated with continuation byte $byte
133 macro_rules! utf8_acc_cont_byte {
134 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
137 #[stable(feature = "rust1", since = "1.0.0")]
138 impl Borrow<str> for String {
140 fn borrow(&self) -> &str { &self[..] }
143 #[stable(feature = "rust1", since = "1.0.0")]
144 impl ToOwned for str {
146 fn to_owned(&self) -> String {
148 String::from_utf8_unchecked(self.as_bytes().to_owned())
153 /// Any string that can be represented as a slice.
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 #[stable(feature = "str_slice_mut", since = "1.5.0")]
281 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
282 core_str::StrExt::slice_mut_unchecked(self, begin, end)
285 /// Given a byte position, return the next code point and its index.
287 /// This can be used to iterate over the Unicode code points of a string.
291 /// If `i` is greater than or equal to the length of the string.
292 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
296 /// This example manually iterates through the code points of a string;
297 /// this should normally be
298 /// done by `.chars()` or `.char_indices()`.
301 /// #![feature(str_char)]
303 /// use std::str::CharRange;
305 /// let s = "中华Việt Nam";
307 /// while i < s.len() {
308 /// let CharRange {ch, next} = s.char_range_at(i);
309 /// println!("{}: {}", i, ch);
330 #[unstable(feature = "str_char",
331 reason = "often replaced by char_indices, this method may \
332 be removed in favor of just char_at() or eventually \
336 pub fn char_range_at(&self, start: usize) -> CharRange {
337 core_str::StrExt::char_range_at(self, start)
340 /// Given a byte position, return the previous `char` and its position.
342 /// This function can be used to iterate over a Unicode code points in reverse.
344 /// Note that Unicode has many features, such as combining marks, ligatures,
345 /// and direction marks, that need to be taken into account to correctly reverse a string.
347 /// Returns 0 for next index if called on start index 0.
351 /// If `i` is greater than the length of the string.
352 /// If `i` is not an index following a valid UTF-8 sequence.
356 /// This example manually iterates through the code points of a string;
357 /// this should normally be
358 /// done by `.chars().rev()` or `.char_indices()`.
361 /// #![feature(str_char)]
363 /// use std::str::CharRange;
365 /// let s = "中华Việt Nam";
366 /// let mut i = s.len();
368 /// let CharRange {ch, next} = s.char_range_at_reverse(i);
369 /// println!("{}: {}", i, ch);
390 #[unstable(feature = "str_char",
391 reason = "often replaced by char_indices, this method may \
392 be removed in favor of just char_at_reverse() or \
393 eventually removed altogether",
396 pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
397 core_str::StrExt::char_range_at_reverse(self, start)
400 /// Given a byte position, return the `char` at that position.
404 /// If `i` is greater than or equal to the length of the string.
405 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
410 /// #![feature(str_char)]
413 /// assert_eq!(s.char_at(1), 'b');
414 /// assert_eq!(s.char_at(2), 'π');
415 /// assert_eq!(s.char_at(4), 'c');
417 #[unstable(feature = "str_char",
418 reason = "frequently replaced by the chars() iterator, this \
419 method may be removed or possibly renamed in the \
420 future; it is normally replaced by chars/char_indices \
421 iterators or by getting the first char from a \
425 pub fn char_at(&self, i: usize) -> char {
426 core_str::StrExt::char_at(self, i)
429 /// Given a byte position, return the `char` at that position, counting
434 /// If `i` is greater than the length of the string.
435 /// If `i` is not an index following a valid UTF-8 sequence.
440 /// #![feature(str_char)]
443 /// assert_eq!(s.char_at_reverse(1), 'a');
444 /// assert_eq!(s.char_at_reverse(2), 'b');
445 /// assert_eq!(s.char_at_reverse(3), 'π');
447 #[unstable(feature = "str_char",
448 reason = "see char_at for more details, but reverse semantics \
449 are also somewhat unclear, especially with which \
450 cases generate panics",
453 pub fn char_at_reverse(&self, i: usize) -> char {
454 core_str::StrExt::char_at_reverse(self, i)
457 /// Retrieves the first code point from a `&str` and returns it.
459 /// Note that a single Unicode character (grapheme cluster)
460 /// can be composed of multiple `char`s.
462 /// This does not allocate a new string; instead, it returns a slice that
463 /// points one code point beyond the code point that was shifted.
465 /// `None` is returned if the slice is empty.
470 /// #![feature(str_char)]
472 /// let s = "Łódź"; // \u{141}o\u{301}dz\u{301}
473 /// let (c, s1) = s.slice_shift_char().unwrap();
475 /// assert_eq!(c, 'Ł');
476 /// assert_eq!(s1, "ódź");
478 /// let (c, s2) = s1.slice_shift_char().unwrap();
480 /// assert_eq!(c, 'o');
481 /// assert_eq!(s2, "\u{301}dz\u{301}");
483 #[unstable(feature = "str_char",
484 reason = "awaiting conventions about shifting and slices and \
485 may not be warranted with the existence of the chars \
486 and/or char_indices iterators",
489 pub fn slice_shift_char(&self) -> Option<(char, &str)> {
490 core_str::StrExt::slice_shift_char(self)
493 /// Divide one string slice into two at an index.
495 /// The index `mid` is a byte offset from the start of the string
496 /// that must be on a `char` boundary.
498 /// Return slices `&self[..mid]` and `&self[mid..]`.
502 /// Panics if `mid` is beyond the last code point of the string,
503 /// or if it is not on a `char` boundary.
507 /// let s = "Löwe 老虎 Léopard";
508 /// let first_space = s.find(' ').unwrap_or(s.len());
509 /// let (a, b) = s.split_at(first_space);
511 /// assert_eq!(a, "Löwe");
512 /// assert_eq!(b, " 老虎 Léopard");
515 #[stable(feature = "str_split_at", since = "1.4.0")]
516 pub fn split_at(&self, mid: usize) -> (&str, &str) {
517 core_str::StrExt::split_at(self, mid)
520 /// Divide one mutable string slice into two at an index.
522 #[stable(feature = "str_split_at", since = "1.4.0")]
523 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
524 core_str::StrExt::split_at_mut(self, mid)
527 /// An iterator over the code points of `self`.
529 /// In Unicode relationship between code points and characters is complex.
530 /// A single character may be composed of multiple code points
531 /// (e.g. diacritical marks added to a letter), and a single code point
532 /// (e.g. Hangul syllable) may contain multiple characters.
534 /// For iteration over human-readable characters a grapheme cluster iterator
535 /// may be more appropriate. See the [unicode-segmentation crate][1].
537 /// [1]: https://crates.io/crates/unicode-segmentation
542 /// let v: Vec<char> = "ASCII żółć 🇨🇭 한".chars().collect();
544 /// assert_eq!(v, ['A', 'S', 'C', 'I', 'I', ' ',
545 /// 'z', '\u{307}', 'o', '\u{301}', 'ł', 'c', '\u{301}', ' ',
546 /// '\u{1f1e8}', '\u{1f1ed}', ' ', '한']);
548 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn chars(&self) -> Chars {
551 core_str::StrExt::chars(self)
554 /// An iterator over the `char`s of `self` and their byte offsets.
559 /// let v: Vec<(usize, char)> = "A🇨🇭".char_indices().collect();
560 /// let b = vec![(0, 'A'), (1, '\u{1f1e8}'), (5, '\u{1f1ed}')];
562 /// assert_eq!(v, b);
564 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn char_indices(&self) -> CharIndices {
567 core_str::StrExt::char_indices(self)
570 /// An iterator over the bytes of `self`.
575 /// let v: Vec<u8> = "bors".bytes().collect();
577 /// assert_eq!(v, b"bors".to_vec());
579 #[stable(feature = "rust1", since = "1.0.0")]
581 pub fn bytes(&self) -> Bytes {
582 core_str::StrExt::bytes(self)
585 /// An iterator over the non-empty substrings of `self` which contain no whitespace,
586 /// and which are separated by any amount of whitespace.
591 /// let some_words = " Mary had\ta\u{2009}little \n\t lamb";
592 /// let v: Vec<&str> = some_words.split_whitespace().collect();
594 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
596 #[stable(feature = "split_whitespace", since = "1.1.0")]
598 pub fn split_whitespace(&self) -> SplitWhitespace {
599 UnicodeStr::split_whitespace(self)
602 /// An iterator over the lines of a string, separated by `\n` or `\r\n`.
604 /// This does not include the empty string after a trailing newline or CRLF.
609 /// let four_lines = "foo\nbar\n\r\nbaz";
610 /// let v: Vec<&str> = four_lines.lines().collect();
612 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
615 /// Leaving off the trailing character:
618 /// let four_lines = "foo\r\nbar\n\nbaz\n";
619 /// let v: Vec<&str> = four_lines.lines().collect();
621 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
623 #[stable(feature = "rust1", since = "1.0.0")]
625 pub fn lines(&self) -> Lines {
626 core_str::StrExt::lines(self)
629 /// An iterator over the lines of a string, separated by either
632 /// As with `.lines()`, this does not include an empty trailing line.
637 /// # #![allow(deprecated)]
638 /// let four_lines = "foo\r\nbar\n\r\nbaz";
639 /// let v: Vec<&str> = four_lines.lines_any().collect();
641 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
644 /// Leaving off the trailing character:
647 /// # #![allow(deprecated)]
648 /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
649 /// let v: Vec<&str> = four_lines.lines_any().collect();
651 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
653 #[stable(feature = "rust1", since = "1.0.0")]
654 #[deprecated(since = "1.4.0", reason = "use lines() instead now")]
657 pub fn lines_any(&self) -> LinesAny {
658 core_str::StrExt::lines_any(self)
661 /// Returns an iterator of `u16` over the string encoded as UTF-16.
662 #[unstable(feature = "str_utf16",
663 reason = "this functionality may only be provided by libunicode",
665 pub fn utf16_units(&self) -> Utf16Units {
666 Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
669 /// Returns `true` if `self` contains another `&str`.
674 /// assert!("bananas".contains("nana"));
676 /// assert!(!"bananas".contains("foobar"));
678 #[stable(feature = "rust1", since = "1.0.0")]
679 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
680 core_str::StrExt::contains(self, pat)
683 /// Returns `true` if the given `&str` is a prefix of the string.
688 /// assert!("banana".starts_with("ba"));
690 #[stable(feature = "rust1", since = "1.0.0")]
691 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
692 core_str::StrExt::starts_with(self, pat)
695 /// Returns true if the given `&str` is a suffix of the string.
700 /// assert!("banana".ends_with("nana"));
702 #[stable(feature = "rust1", since = "1.0.0")]
703 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
704 where P::Searcher: ReverseSearcher<'a>
706 core_str::StrExt::ends_with(self, pat)
709 /// Returns the byte index of the first character of `self` that matches
710 /// the pattern, if it
713 /// Returns `None` if it doesn't exist.
715 /// The pattern can be a simple `&str`, `char`, or a closure that
716 /// determines if a character matches.
723 /// let s = "Löwe 老虎 Léopard";
725 /// assert_eq!(s.find('L'), Some(0));
726 /// assert_eq!(s.find('é'), Some(14));
727 /// assert_eq!(s.find("Léopard"), Some(13));
731 /// More complex patterns with closures:
734 /// let s = "Löwe 老虎 Léopard";
736 /// assert_eq!(s.find(char::is_whitespace), Some(5));
737 /// assert_eq!(s.find(char::is_lowercase), Some(1));
740 /// Not finding the pattern:
743 /// let s = "Löwe 老虎 Léopard";
744 /// let x: &[_] = &['1', '2'];
746 /// assert_eq!(s.find(x), None);
748 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
750 core_str::StrExt::find(self, pat)
753 /// Returns the byte index of the last character of `self` that
754 /// matches the pattern, if it
757 /// Returns `None` if it doesn't exist.
759 /// The pattern can be a simple `&str`, `char`,
760 /// or a closure that determines if a character matches.
767 /// let s = "Löwe 老虎 Léopard";
769 /// assert_eq!(s.rfind('L'), Some(13));
770 /// assert_eq!(s.rfind('é'), Some(14));
773 /// More complex patterns with closures:
776 /// let s = "Löwe 老虎 Léopard";
778 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
779 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
782 /// Not finding the pattern:
785 /// let s = "Löwe 老虎 Léopard";
786 /// let x: &[_] = &['1', '2'];
788 /// assert_eq!(s.rfind(x), None);
790 #[stable(feature = "rust1", since = "1.0.0")]
791 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
792 where P::Searcher: ReverseSearcher<'a>
794 core_str::StrExt::rfind(self, pat)
797 /// An iterator over substrings of `self`, separated by characters
798 /// matched by a pattern.
800 /// The pattern can be a simple `&str`, `char`, or a closure that
801 /// determines the split. Additional libraries might provide more complex
802 /// patterns like regular expressions.
804 /// # Iterator behavior
806 /// The returned iterator will be double ended if the pattern allows a
807 /// reverse search and forward/reverse search yields the same elements.
808 /// This is true for, eg, `char` but not
811 /// If the pattern allows a reverse search but its results might differ
812 /// from a forward search, `rsplit()` can be used.
819 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
820 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
822 /// let v: Vec<&str> = "".split('X').collect();
823 /// assert_eq!(v, [""]);
825 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
826 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
828 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
829 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
831 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
832 /// assert_eq!(v, ["abc", "def", "ghi"]);
834 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
835 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
838 /// A more complex pattern, using a closure:
841 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
842 /// assert_eq!(v, ["abc", "def", "ghi"]);
845 /// If a string contains multiple contiguous separators, you will end up
846 /// with empty strings in the output:
849 /// let x = "||||a||b|c".to_string();
850 /// let d: Vec<_> = x.split('|').collect();
852 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
855 /// This can lead to possibly surprising behavior when whitespace is used
856 /// as the separator. This code is correct:
859 /// let x = " a b c".to_string();
860 /// let d: Vec<_> = x.split(' ').collect();
862 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
865 /// It does _not_ give you:
868 /// assert_eq!(d, &["a", "b", "c"]);
871 /// Use [`.split_whitespace()`][split_whitespace] for this behavior.
873 /// [split_whitespace]: #method.split_whitespace
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 if a character matches.
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 if a character matches.
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 disjoint matches of a pattern within `self` as well
1163 /// as the index that the match starts at.
1165 /// For matches of `pat` within `self` that overlap, only the indices
1166 /// corresponding to the first match are returned.
1168 /// The pattern can be a simple `&str`, `char`, or a closure that determines
1169 /// if a character matches. Additional libraries might provide more complex
1170 /// patterns like regular expressions.
1172 /// # Iterator behavior
1174 /// The returned iterator will be double ended if the pattern allows a
1175 /// reverse search and forward/reverse search yields the same elements. This
1176 /// is true for, eg, `char` but not for `&str`.
1178 /// If the pattern allows a reverse search but its results might differ
1179 /// from a forward search, `rmatch_indices()` can be used.
1184 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1185 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1187 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1188 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1190 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1191 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1193 #[stable(feature = "str_match_indices", since = "1.5.0")]
1194 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1195 core_str::StrExt::match_indices(self, pat)
1198 /// An iterator over the disjoint matches of a pattern within `self`,
1199 /// yielded in reverse order along with the index of the match.
1201 /// For matches of `pat` within `self` that overlap, only the indices
1202 /// corresponding to the last match are returned.
1204 /// The pattern can be a simple `&str`, `char`, or a closure that determines
1205 /// if a character matches. Additional libraries might provide more complex
1206 /// patterns like regular expressions.
1208 /// # Iterator behavior
1210 /// The returned iterator requires that the pattern supports a reverse
1211 /// search, and it will be double ended if a forward/reverse search yields
1212 /// the same elements.
1214 /// For iterating from the front, `match_indices()` can be used.
1219 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1220 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1222 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1223 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1225 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1226 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1228 #[stable(feature = "str_match_indices", since = "1.5.0")]
1229 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1230 where P::Searcher: ReverseSearcher<'a>
1232 core_str::StrExt::rmatch_indices(self, pat)
1235 /// Returns a `&str` with leading and trailing whitespace removed.
1240 /// let s = " Hello\tworld\t";
1241 /// assert_eq!(s.trim(), "Hello\tworld");
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 pub fn trim(&self) -> &str {
1245 UnicodeStr::trim(self)
1248 /// Returns a `&str` with leading whitespace removed.
1253 /// let s = " Hello\tworld\t";
1254 /// assert_eq!(s.trim_left(), "Hello\tworld\t");
1256 #[stable(feature = "rust1", since = "1.0.0")]
1257 pub fn trim_left(&self) -> &str {
1258 UnicodeStr::trim_left(self)
1261 /// Returns a `&str` with trailing whitespace removed.
1266 /// let s = " Hello\tworld\t";
1267 /// assert_eq!(s.trim_right(), " Hello\tworld");
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 pub fn trim_right(&self) -> &str {
1271 UnicodeStr::trim_right(self)
1274 /// Returns a string with all pre- and suffixes that match a pattern
1275 /// repeatedly removed.
1277 /// The pattern can be a simple `char`, or a closure that determines
1278 /// if a character matches.
1282 /// Simple patterns:
1285 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1286 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1288 /// let x: &[_] = &['1', '2'];
1289 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1292 /// A more complex pattern, using a closure:
1295 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1299 where P::Searcher: DoubleEndedSearcher<'a>
1301 core_str::StrExt::trim_matches(self, pat)
1304 /// Returns a string with all prefixes that match a pattern
1305 /// repeatedly removed.
1307 /// The pattern can be a simple `&str`, `char`, or a closure that
1308 /// determines if a character matches.
1313 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1314 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1316 /// let x: &[_] = &['1', '2'];
1317 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1321 core_str::StrExt::trim_left_matches(self, pat)
1324 /// Returns a string with all suffixes that match a pattern
1325 /// repeatedly removed.
1327 /// The pattern can be a simple `&str`, `char`, or a closure that
1328 /// determines if a character matches.
1332 /// Simple patterns:
1335 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1336 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1338 /// let x: &[_] = &['1', '2'];
1339 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1342 /// A more complex pattern, using a closure:
1345 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1349 where P::Searcher: ReverseSearcher<'a>
1351 core_str::StrExt::trim_right_matches(self, pat)
1354 /// Parses `self` into the specified type.
1358 /// Will return `Err` if it's not possible to parse `self` into the type.
1363 /// assert_eq!("4".parse::<u32>(), Ok(4));
1369 /// assert!("j".parse::<u32>().is_err());
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1374 core_str::StrExt::parse(self)
1377 /// Replaces all occurrences of one string with another.
1379 /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a
1380 /// second `&str` to
1381 /// replace it with. If the original `&str` isn't found, no change occurs.
1386 /// let s = "this is old";
1388 /// assert_eq!(s.replace("old", "new"), "this is new");
1391 /// When a `&str` isn't found:
1394 /// let s = "this is old";
1395 /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 pub fn replace(&self, from: &str, to: &str) -> String {
1399 let mut result = String::new();
1400 let mut last_end = 0;
1401 for (start, part) in self.match_indices(from) {
1402 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1403 result.push_str(to);
1404 last_end = start + part.len();
1406 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1410 /// Returns the lowercase equivalent of this string.
1415 /// let s = "HELLO";
1416 /// assert_eq!(s.to_lowercase(), "hello");
1418 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1419 pub fn to_lowercase(&self) -> String {
1420 let mut s = String::with_capacity(self.len());
1421 for (i, c) in self[..].char_indices() {
1423 // Σ maps to σ, except at the end of a word where it maps to ς.
1424 // This is the only conditional (contextual) but language-independent mapping
1425 // in `SpecialCasing.txt`,
1426 // so hard-code it rather than have a generic "condition" mechanim.
1427 // See https://github.com/rust-lang/rust/issues/26035
1428 map_uppercase_sigma(self, i, &mut s)
1430 s.extend(c.to_lowercase());
1435 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1436 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1437 // for the definition of `Final_Sigma`.
1438 debug_assert!('Σ'.len_utf8() == 2);
1440 case_ignoreable_then_cased(from[..i].chars().rev()) &&
1441 !case_ignoreable_then_cased(from[i + 2..].chars());
1442 to.push_str(if is_word_final { "ς" } else { "σ" });
1445 fn case_ignoreable_then_cased<I: Iterator<Item=char>>(iter: I) -> bool {
1446 use rustc_unicode::derived_property::{Cased, Case_Ignorable};
1447 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1448 Some(c) => Cased(c),
1454 /// Returns the uppercase equivalent of this string.
1459 /// let s = "hello";
1460 /// assert_eq!(s.to_uppercase(), "HELLO");
1462 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1463 pub fn to_uppercase(&self) -> String {
1464 let mut s = String::with_capacity(self.len());
1465 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1469 /// Escapes each char in `s` with `char::escape_default`.
1470 #[unstable(feature = "str_escape",
1471 reason = "return type may change to be an iterator",
1473 pub fn escape_default(&self) -> String {
1474 self.chars().flat_map(|c| c.escape_default()).collect()
1477 /// Escapes each char in `s` with `char::escape_unicode`.
1478 #[unstable(feature = "str_escape",
1479 reason = "return type may change to be an iterator",
1481 pub fn escape_unicode(&self) -> String {
1482 self.chars().flat_map(|c| c.escape_unicode()).collect()
1485 /// Converts the `Box<str>` into a `String` without copying or allocating.
1486 #[stable(feature = "box_str", since = "1.4.0")]
1487 pub fn into_string(self: Box<str>) -> String {
1489 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1490 String::from_utf8_unchecked(slice.into_vec())