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 self::RecompositionState::*;
23 use self::DecompositionType::*;
25 use core::clone::Clone;
26 use core::iter::{Iterator, Extend};
27 use core::option::Option::{self, Some, None};
28 use core::result::Result;
29 use core::str as core_str;
30 use core::str::pattern::Pattern;
31 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
33 use rustc_unicode::str::{UnicodeStr, Utf16Encoder};
35 use vec_deque::VecDeque;
36 use borrow::{Borrow, ToOwned};
40 use slice::SliceConcatExt;
43 pub use core::str::{FromStr, Utf8Error};
44 pub use core::str::{Lines, LinesAny, CharRange};
45 pub use core::str::{Split, RSplit};
46 pub use core::str::{SplitN, RSplitN};
47 pub use core::str::{SplitTerminator, RSplitTerminator};
48 pub use core::str::{Matches, RMatches};
49 pub use core::str::{MatchIndices, RMatchIndices};
50 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
51 pub use core::str::{from_utf8_unchecked, ParseBoolError};
52 pub use rustc_unicode::str::{SplitWhitespace, Words, Graphemes, GraphemeIndices};
53 pub use core::str::pattern;
55 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
58 fn concat(&self) -> String {
63 // `len` calculation may overflow but push_str will check boundaries
64 let len = self.iter().map(|s| s.borrow().len()).sum();
65 let mut result = String::with_capacity(len);
68 result.push_str(s.borrow())
74 fn join(&self, sep: &str) -> String {
84 // this is wrong without the guarantee that `self` is non-empty
85 // `len` calculation may overflow but push_str but will check boundaries
86 let len = sep.len() * (self.len() - 1)
87 + self.iter().map(|s| s.borrow().len()).sum::<usize>();
88 let mut result = String::with_capacity(len);
97 result.push_str(s.borrow());
102 fn connect(&self, sep: &str) -> String {
107 // Helper functions used for Unicode normalization
108 fn canonical_sort(comb: &mut [(char, u8)]) {
109 let len = comb.len();
111 let mut swapped = false;
113 let class_a = comb[j-1].1;
114 let class_b = comb[j].1;
115 if class_a != 0 && class_b != 0 && class_a > class_b {
120 if !swapped { break; }
125 enum DecompositionType {
130 /// External iterator for a string decomposition's characters.
132 /// For use with the `std::iter` module.
134 #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
137 #[unstable(feature = "unicode",
138 reason = "this functionality may be replaced with a more generic \
139 unicode crate on crates.io")]
140 pub struct Decompositions<'a> {
141 kind: DecompositionType,
143 buffer: Vec<(char, u8)>,
148 #[stable(feature = "rust1", since = "1.0.0")]
149 impl<'a> Iterator for Decompositions<'a> {
153 fn next(&mut self) -> Option<char> {
154 match self.buffer.first() {
157 self.buffer.remove(0);
160 Some(&(c, _)) if self.sorted => {
161 self.buffer.remove(0);
164 _ => self.sorted = false
168 for ch in self.iter.by_ref() {
169 let buffer = &mut self.buffer;
170 let sorted = &mut self.sorted;
174 rustc_unicode::char::canonical_combining_class(d);
175 if class == 0 && !*sorted {
176 canonical_sort(buffer);
179 buffer.push((d, class));
183 rustc_unicode::char::decompose_canonical(ch, callback)
186 rustc_unicode::char::decompose_compatible(ch, callback)
197 canonical_sort(&mut self.buffer);
201 if self.buffer.is_empty() {
204 match self.buffer.remove(0) {
214 fn size_hint(&self) -> (usize, Option<usize>) {
215 let (lower, _) = self.iter.size_hint();
221 enum RecompositionState {
227 /// External iterator for a string recomposition's characters.
229 /// For use with the `std::iter` module.
231 #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
234 #[unstable(feature = "unicode",
235 reason = "this functionality may be replaced with a more generic \
236 unicode crate on crates.io")]
237 pub struct Recompositions<'a> {
238 iter: Decompositions<'a>,
239 state: RecompositionState,
240 buffer: VecDeque<char>,
241 composee: Option<char>,
246 #[stable(feature = "rust1", since = "1.0.0")]
247 impl<'a> Iterator for Recompositions<'a> {
251 fn next(&mut self) -> Option<char> {
255 for ch in self.iter.by_ref() {
256 let ch_class = rustc_unicode::char::canonical_combining_class(ch);
257 if self.composee.is_none() {
261 self.composee = Some(ch);
264 let k = self.composee.clone().unwrap();
266 match self.last_ccc {
268 match rustc_unicode::char::compose(k, ch) {
270 self.composee = Some(r);
275 self.composee = Some(ch);
278 self.buffer.push_back(ch);
279 self.last_ccc = Some(ch_class);
284 if l_class >= ch_class {
285 // `ch` is blocked from `composee`
287 self.composee = Some(ch);
288 self.last_ccc = None;
289 self.state = Purging;
292 self.buffer.push_back(ch);
293 self.last_ccc = Some(ch_class);
296 match rustc_unicode::char::compose(k, ch) {
298 self.composee = Some(r);
302 self.buffer.push_back(ch);
303 self.last_ccc = Some(ch_class);
309 self.state = Finished;
310 if self.composee.is_some() {
311 return self.composee.take();
315 match self.buffer.pop_front() {
316 None => self.state = Composing,
321 match self.buffer.pop_front() {
322 None => return self.composee.take(),
331 /// External iterator for a string's UTF16 codeunits.
333 /// For use with the `std::iter` module.
335 #[unstable(feature = "str_utf16")]
336 pub struct Utf16Units<'a> {
337 encoder: Utf16Encoder<Chars<'a>>
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl<'a> Iterator for Utf16Units<'a> {
345 fn next(&mut self) -> Option<u16> { self.encoder.next() }
348 fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
351 // Return the initial codepoint accumulator for the first byte.
352 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
353 // for width 3, and 3 bits for width 4
354 macro_rules! utf8_first_byte {
355 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
358 // return the value of $ch updated with continuation byte $byte
359 macro_rules! utf8_acc_cont_byte {
360 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
363 #[stable(feature = "rust1", since = "1.0.0")]
364 impl Borrow<str> for String {
366 fn borrow(&self) -> &str { &self[..] }
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl ToOwned for str {
372 fn to_owned(&self) -> String {
374 String::from_utf8_unchecked(self.as_bytes().to_owned())
379 /// Any string that can be represented as a slice.
382 #[stable(feature = "rust1", since = "1.0.0")]
384 /// Returns the length of `self` in bytes.
389 /// assert_eq!("foo".len(), 3);
390 /// assert_eq!("ƒoo".len(), 4); // fancy f!
392 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn len(&self) -> usize {
395 core_str::StrExt::len(self)
398 /// Returns true if this slice has a length of zero bytes.
403 /// assert!("".is_empty());
406 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn is_empty(&self) -> bool {
408 core_str::StrExt::is_empty(self)
411 /// Returns a string's displayed width in columns.
413 /// Control characters have zero width.
415 /// `is_cjk` determines behavior for characters in the Ambiguous category:
417 /// `true`, these are 2 columns wide; otherwise, they are 1.
418 /// In CJK locales, `is_cjk` should be
419 /// `true`, else it should be `false`.
420 /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/)
421 /// recommends that these
422 /// characters be treated as 1 column (i.e., `is_cjk = false`) if the
423 /// locale is unknown.
424 #[deprecated(reason = "use the crates.io `unicode-width` library instead",
426 #[unstable(feature = "unicode",
427 reason = "this functionality may only be provided by libunicode")]
429 pub fn width(&self, is_cjk: bool) -> usize {
430 UnicodeStr::width(self, is_cjk)
433 /// Checks that `index`-th byte lies at the start and/or end of a
434 /// UTF-8 code point sequence.
436 /// The start and end of the string (when `index == self.len()`) are
440 /// Returns `false` if `index` is greater than `self.len()`.
445 /// #![feature(str_char)]
447 /// let s = "Löwe 老虎 Léopard";
448 /// assert!(s.is_char_boundary(0));
450 /// assert!(s.is_char_boundary(6));
451 /// assert!(s.is_char_boundary(s.len()));
453 /// // second byte of `ö`
454 /// assert!(!s.is_char_boundary(2));
456 /// // third byte of `老`
457 /// assert!(!s.is_char_boundary(8));
459 #[unstable(feature = "str_char",
460 reason = "it is unclear whether this method pulls its weight \
461 with the existence of the char_indices iterator or \
462 this method may want to be replaced with checked \
465 pub fn is_char_boundary(&self, index: usize) -> bool {
466 core_str::StrExt::is_char_boundary(self, index)
469 /// Converts `self` to a byte slice.
474 /// assert_eq!("bors".as_bytes(), b"bors");
476 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn as_bytes(&self) -> &[u8] {
479 core_str::StrExt::as_bytes(self)
482 /// Converts `self` to a mutable byte slice.
486 /// The `str` type guarantees that its contents are UTF-8 bytes, which can
487 /// be violated using this function, leading to memory-unsafeties in other
488 /// string functions.
489 #[unstable(feature = "str_as_bytes_mut")]
491 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
492 core_str::StrExt::as_bytes_mut(self)
495 /// Returns a raw pointer to the `&str`'s buffer.
497 /// The caller must ensure that the string outlives this pointer, and
499 /// reallocated (e.g. by pushing to the string).
505 /// let p = s.as_ptr();
507 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn as_ptr(&self) -> *const u8 {
510 core_str::StrExt::as_ptr(self)
513 /// Takes a bytewise slice from a string.
515 /// Returns the substring from [`begin`..`end`).
519 /// Caller must check both UTF-8 sequence boundaries and the boundaries
520 /// of the entire slice as well.
525 /// let s = "Löwe 老虎 Léopard";
528 /// assert_eq!(s.slice_unchecked(0, 21), "Löwe 老虎 Léopard");
531 #[stable(feature = "rust1", since = "1.0.0")]
533 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
534 core_str::StrExt::slice_unchecked(self, begin, end)
537 /// Takes a bytewise mutable slice from a string.
539 /// Same as `slice_unchecked`, but works with `&mut str` instead of `&str`.
540 #[unstable(feature = "str_slice_mut", reason = "recently added")]
542 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
543 core_str::StrExt::slice_mut_unchecked(self, begin, end)
546 /// Returns a slice of the string from the range [`begin`..`end`) where indices
547 /// are counted in code points.
549 /// That is, start at the `begin`-th code point of the string and continue
550 /// to the `end`-th code point. This does not detect or handle edge cases
551 /// such as leaving a combining character as the first `char` of the
554 /// Due to the design of UTF-8, this operation is `O(end)`. Use slicing
555 /// syntax if you want to use `O(1)` byte indices instead.
559 /// Panics if `begin` > `end` or the either `begin` or `end` are beyond the
560 /// last character of the string.
565 /// #![feature(slice_chars)]
567 /// let s = "Löwe 老虎 Léopard";
569 /// assert_eq!(s.slice_chars(0, 4), "Löwe");
570 /// assert_eq!(s.slice_chars(5, 7), "老虎");
572 #[unstable(feature = "slice_chars",
573 reason = "may have yet to prove its worth")]
574 #[deprecated(since = "1.3.0",
575 reason = "can be implemented with char_indices and \
576 hasn't seen enough use to justify inclusion")]
578 pub fn slice_chars(&self, begin: usize, end: usize) -> &str {
579 core_str::StrExt::slice_chars(self, begin, end)
582 /// Given a byte position, return the next code point and its index.
584 /// This can be used to iterate over the Unicode code points of a string.
588 /// If `i` is greater than or equal to the length of the string.
589 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
593 /// This example manually iterates through the code points of a string;
594 /// this should normally be
595 /// done by `.chars()` or `.char_indices()`.
598 /// #![feature(str_char, core)]
600 /// use std::str::CharRange;
602 /// let s = "中华Việt Nam";
604 /// while i < s.len() {
605 /// let CharRange {ch, next} = s.char_range_at(i);
606 /// println!("{}: {}", i, ch);
627 #[unstable(feature = "str_char",
628 reason = "often replaced by char_indices, this method may \
629 be removed in favor of just char_at() or eventually \
630 removed altogether")]
632 pub fn char_range_at(&self, start: usize) -> CharRange {
633 core_str::StrExt::char_range_at(self, start)
636 /// Given a byte position, return the previous `char` and its position.
638 /// This function can be used to iterate over a Unicode code points in reverse.
640 /// Note that Unicode has many features, such as combining marks, ligatures,
641 /// and direction marks, that need to be taken into account to correctly reverse a string.
643 /// Returns 0 for next index if called on start index 0.
647 /// If `i` is greater than the length of the string.
648 /// If `i` is not an index following a valid UTF-8 sequence.
652 /// This example manually iterates through the code points of a string;
653 /// this should normally be
654 /// done by `.chars().rev()` or `.char_indices()`.
657 /// #![feature(str_char, core)]
659 /// use std::str::CharRange;
661 /// let s = "中华Việt Nam";
662 /// let mut i = s.len();
664 /// let CharRange {ch, next} = s.char_range_at_reverse(i);
665 /// println!("{}: {}", i, ch);
686 #[unstable(feature = "str_char",
687 reason = "often replaced by char_indices, this method may \
688 be removed in favor of just char_at_reverse() or \
689 eventually removed altogether")]
691 pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
692 core_str::StrExt::char_range_at_reverse(self, start)
695 /// Given a byte position, return the `char` at that position.
699 /// If `i` is greater than or equal to the length of the string.
700 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
705 /// #![feature(str_char)]
708 /// assert_eq!(s.char_at(1), 'b');
709 /// assert_eq!(s.char_at(2), 'π');
710 /// assert_eq!(s.char_at(4), 'c');
712 #[unstable(feature = "str_char",
713 reason = "frequently replaced by the chars() iterator, this \
714 method may be removed or possibly renamed in the \
715 future; it is normally replaced by chars/char_indices \
716 iterators or by getting the first char from a \
719 pub fn char_at(&self, i: usize) -> char {
720 core_str::StrExt::char_at(self, i)
723 /// Given a byte position, return the `char` at that position, counting
728 /// If `i` is greater than the length of the string.
729 /// If `i` is not an index following a valid UTF-8 sequence.
734 /// #![feature(str_char)]
737 /// assert_eq!(s.char_at_reverse(1), 'a');
738 /// assert_eq!(s.char_at_reverse(2), 'b');
739 /// assert_eq!(s.char_at_reverse(3), 'π');
741 #[unstable(feature = "str_char",
742 reason = "see char_at for more details, but reverse semantics \
743 are also somewhat unclear, especially with which \
744 cases generate panics")]
746 pub fn char_at_reverse(&self, i: usize) -> char {
747 core_str::StrExt::char_at_reverse(self, i)
750 /// Retrieves the first code point from a `&str` and returns it.
752 /// Note that a single Unicode character (grapheme cluster)
753 /// can be composed of multiple `char`s.
755 /// This does not allocate a new string; instead, it returns a slice that
756 /// points one code point beyond the code point that was shifted.
758 /// `None` is returned if the slice is empty.
763 /// #![feature(str_char)]
765 /// let s = "Łódź"; // \u{141}o\u{301}dz\u{301}
766 /// let (c, s1) = s.slice_shift_char().unwrap();
768 /// assert_eq!(c, 'Ł');
769 /// assert_eq!(s1, "ódź");
771 /// let (c, s2) = s1.slice_shift_char().unwrap();
773 /// assert_eq!(c, 'o');
774 /// assert_eq!(s2, "\u{301}dz\u{301}");
776 #[unstable(feature = "str_char",
777 reason = "awaiting conventions about shifting and slices and \
778 may not be warranted with the existence of the chars \
779 and/or char_indices iterators")]
781 pub fn slice_shift_char(&self) -> Option<(char, &str)> {
782 core_str::StrExt::slice_shift_char(self)
785 /// Divide one string slice into two at an index.
787 /// The index `mid` is a byte offset from the start of the string
788 /// that must be on a `char` boundary.
790 /// Return slices `&self[..mid]` and `&self[mid..]`.
794 /// Panics if `mid` is beyond the last code point of the string,
795 /// or if it is not on a `char` boundary.
799 /// #![feature(str_split_at)]
801 /// let s = "Löwe 老虎 Léopard";
802 /// let first_space = s.find(' ').unwrap_or(s.len());
803 /// let (a, b) = s.split_at(first_space);
805 /// assert_eq!(a, "Löwe");
806 /// assert_eq!(b, " 老虎 Léopard");
809 #[unstable(feature = "str_split_at", reason = "recently added")]
810 pub fn split_at(&self, mid: usize) -> (&str, &str) {
811 core_str::StrExt::split_at(self, mid)
814 /// Divide one mutable string slice into two at an index.
816 #[unstable(feature = "str_split_at", reason = "recently added")]
817 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
818 core_str::StrExt::split_at_mut(self, mid)
821 /// An iterator over the code points of `self`.
823 /// In Unicode relationship between code points and characters is complex.
824 /// A single character may be composed of multiple code points
825 /// (e.g. diacritical marks added to a letter), and a single code point
826 /// (e.g. Hangul syllable) may contain multiple characters.
828 /// For iteration over human-readable characters a grapheme cluster iterator
829 /// may be more appropriate. See the [unicode-segmentation crate][1].
831 /// [1]: https://crates.io/crates/unicode-segmentation
836 /// let v: Vec<char> = "ASCII żółć 🇨🇭 한".chars().collect();
838 /// assert_eq!(v, ['A', 'S', 'C', 'I', 'I', ' ',
839 /// 'z', '\u{307}', 'o', '\u{301}', 'ł', 'c', '\u{301}', ' ',
840 /// '\u{1f1e8}', '\u{1f1ed}', ' ', '한']);
842 #[stable(feature = "rust1", since = "1.0.0")]
844 pub fn chars(&self) -> Chars {
845 core_str::StrExt::chars(self)
848 /// An iterator over the `char`s of `self` and their byte offsets.
853 /// let v: Vec<(usize, char)> = "A🇨🇭".char_indices().collect();
854 /// let b = vec![(0, 'A'), (1, '\u{1f1e8}'), (5, '\u{1f1ed}')];
856 /// assert_eq!(v, b);
858 #[stable(feature = "rust1", since = "1.0.0")]
860 pub fn char_indices(&self) -> CharIndices {
861 core_str::StrExt::char_indices(self)
864 /// An iterator over the bytes of `self`.
869 /// let v: Vec<u8> = "bors".bytes().collect();
871 /// assert_eq!(v, b"bors".to_vec());
873 #[stable(feature = "rust1", since = "1.0.0")]
875 pub fn bytes(&self) -> Bytes {
876 core_str::StrExt::bytes(self)
879 /// An iterator over the non-empty substrings of `self` which contain no whitespace,
880 /// and which are separated by any amount of whitespace.
885 /// let some_words = " Mary had\ta\u{2009}little \n\t lamb";
886 /// let v: Vec<&str> = some_words.split_whitespace().collect();
888 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
890 #[stable(feature = "split_whitespace", since = "1.1.0")]
892 pub fn split_whitespace(&self) -> SplitWhitespace {
893 UnicodeStr::split_whitespace(self)
896 /// An iterator over the non-empty substrings of `self` which contain no whitespace,
897 /// and which are separated by any amount of whitespace.
902 /// #![feature(str_words)]
903 /// #![allow(deprecated)]
905 /// let some_words = " Mary had\ta\u{2009}little \n\t lamb";
906 /// let v: Vec<&str> = some_words.words().collect();
908 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
910 #[deprecated(reason = "words() will be removed. Use split_whitespace() instead",
912 #[unstable(feature = "str_words",
913 reason = "the precise algorithm to use is unclear")]
916 pub fn words(&self) -> Words {
917 UnicodeStr::words(self)
920 /// An iterator over the lines of a string, separated by `\n`.
922 /// This does not include the empty string after a trailing `\n`.
927 /// let four_lines = "foo\nbar\n\nbaz";
928 /// let v: Vec<&str> = four_lines.lines().collect();
930 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
933 /// Leaving off the trailing character:
936 /// let four_lines = "foo\nbar\n\nbaz\n";
937 /// let v: Vec<&str> = four_lines.lines().collect();
939 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
941 #[stable(feature = "rust1", since = "1.0.0")]
943 pub fn lines(&self) -> Lines {
944 core_str::StrExt::lines(self)
947 /// An iterator over the lines of a string, separated by either
950 /// As with `.lines()`, this does not include an empty trailing line.
955 /// let four_lines = "foo\r\nbar\n\r\nbaz";
956 /// let v: Vec<&str> = four_lines.lines_any().collect();
958 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
961 /// Leaving off the trailing character:
964 /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
965 /// let v: Vec<&str> = four_lines.lines_any().collect();
967 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
969 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn lines_any(&self) -> LinesAny {
972 core_str::StrExt::lines_any(self)
975 /// Returns an iterator over the string in Unicode Normalization Form D
976 /// (canonical decomposition).
978 #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
981 #[unstable(feature = "unicode",
982 reason = "this functionality may be replaced with a more generic \
983 unicode crate on crates.io")]
984 pub fn nfd_chars(&self) -> Decompositions {
986 iter: self[..].chars(),
993 /// Returns an iterator over the string in Unicode Normalization Form KD
994 /// (compatibility decomposition).
996 #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
999 #[unstable(feature = "unicode",
1000 reason = "this functionality may be replaced with a more generic \
1001 unicode crate on crates.io")]
1002 pub fn nfkd_chars(&self) -> Decompositions {
1004 iter: self[..].chars(),
1011 /// An Iterator over the string in Unicode Normalization Form C
1012 /// (canonical decomposition followed by canonical composition).
1013 #[allow(deprecated)]
1014 #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
1017 #[unstable(feature = "unicode",
1018 reason = "this functionality may be replaced with a more generic \
1019 unicode crate on crates.io")]
1020 pub fn nfc_chars(&self) -> Recompositions {
1022 iter: self.nfd_chars(),
1024 buffer: VecDeque::new(),
1030 /// An Iterator over the string in Unicode Normalization Form KC
1031 /// (compatibility decomposition followed by canonical composition).
1032 #[allow(deprecated)]
1033 #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
1036 #[unstable(feature = "unicode",
1037 reason = "this functionality may be replaced with a more generic \
1038 unicode crate on crates.io")]
1039 pub fn nfkc_chars(&self) -> Recompositions {
1041 iter: self.nfkd_chars(),
1043 buffer: VecDeque::new(),
1049 /// Returns an iterator over the [grapheme clusters][graphemes] of `self`.
1051 /// [graphemes]: http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
1053 /// If `is_extended` is true, the iterator is over the
1054 /// *extended grapheme clusters*;
1055 /// otherwise, the iterator is over the *legacy grapheme clusters*.
1056 /// [UAX#29](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
1057 /// recommends extended grapheme cluster boundaries for general processing.
1062 /// #![feature(unicode, core)]
1064 /// let gr1 = "a\u{310}e\u{301}o\u{308}\u{332}".graphemes(true).collect::<Vec<&str>>();
1065 /// let b: &[_] = &["a\u{310}", "e\u{301}", "o\u{308}\u{332}"];
1067 /// assert_eq!(&gr1[..], b);
1069 /// let gr2 = "a\r\nb🇷🇺🇸🇹".graphemes(true).collect::<Vec<&str>>();
1070 /// let b: &[_] = &["a", "\r\n", "b", "🇷🇺🇸🇹"];
1072 /// assert_eq!(&gr2[..], b);
1074 #[deprecated(reason = "use the crates.io `unicode-segmentation` library instead",
1076 #[unstable(feature = "unicode",
1077 reason = "this functionality may only be provided by libunicode")]
1078 pub fn graphemes(&self, is_extended: bool) -> Graphemes {
1079 UnicodeStr::graphemes(self, is_extended)
1082 /// Returns an iterator over the grapheme clusters of `self` and their
1083 /// byte offsets. See
1084 /// `graphemes()` for more information.
1089 /// #![feature(unicode, core)]
1091 /// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(usize, &str)>>();
1092 /// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
1094 /// assert_eq!(&gr_inds[..], b);
1096 #[deprecated(reason = "use the crates.io `unicode-segmentation` library instead",
1098 #[unstable(feature = "unicode",
1099 reason = "this functionality may only be provided by libunicode")]
1100 pub fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices {
1101 UnicodeStr::grapheme_indices(self, is_extended)
1104 /// Returns an iterator of `u16` over the string encoded as UTF-16.
1105 #[unstable(feature = "str_utf16",
1106 reason = "this functionality may only be provided by libunicode")]
1107 pub fn utf16_units(&self) -> Utf16Units {
1108 Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
1111 /// Returns `true` if `self` contains another `&str`.
1116 /// assert!("bananas".contains("nana"));
1118 /// assert!(!"bananas".contains("foobar"));
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1122 core_str::StrExt::contains(self, pat)
1125 /// Returns `true` if the given `&str` is a prefix of the string.
1130 /// assert!("banana".starts_with("ba"));
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1134 core_str::StrExt::starts_with(self, pat)
1137 /// Returns true if the given `&str` is a suffix of the string.
1142 /// assert!("banana".ends_with("nana"));
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1146 where P::Searcher: ReverseSearcher<'a>
1148 core_str::StrExt::ends_with(self, pat)
1151 /// Returns the byte index of the first character of `self` that matches
1152 /// the pattern, if it
1155 /// Returns `None` if it doesn't exist.
1157 /// The pattern can be a simple `&str`, `char`, or a closure that
1163 /// Simple patterns:
1166 /// let s = "Löwe 老虎 Léopard";
1168 /// assert_eq!(s.find('L'), Some(0));
1169 /// assert_eq!(s.find('é'), Some(14));
1170 /// assert_eq!(s.find("Léopard"), Some(13));
1174 /// More complex patterns with closures:
1177 /// let s = "Löwe 老虎 Léopard";
1179 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1180 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1183 /// Not finding the pattern:
1186 /// let s = "Löwe 老虎 Léopard";
1187 /// let x: &[_] = &['1', '2'];
1189 /// assert_eq!(s.find(x), None);
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1193 core_str::StrExt::find(self, pat)
1196 /// Returns the byte index of the last character of `self` that
1197 /// matches the pattern, if it
1200 /// Returns `None` if it doesn't exist.
1202 /// The pattern can be a simple `&str`, `char`,
1203 /// or a closure that determines the split.
1207 /// Simple patterns:
1210 /// let s = "Löwe 老虎 Léopard";
1212 /// assert_eq!(s.rfind('L'), Some(13));
1213 /// assert_eq!(s.rfind('é'), Some(14));
1216 /// More complex patterns with closures:
1219 /// let s = "Löwe 老虎 Léopard";
1221 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1222 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1225 /// Not finding the pattern:
1228 /// let s = "Löwe 老虎 Léopard";
1229 /// let x: &[_] = &['1', '2'];
1231 /// assert_eq!(s.rfind(x), None);
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1235 where P::Searcher: ReverseSearcher<'a>
1237 core_str::StrExt::rfind(self, pat)
1240 /// An iterator over substrings of `self`, separated by characters
1241 /// matched by a pattern.
1243 /// The pattern can be a simple `&str`, `char`, or a closure that
1244 /// determines the split. Additional libraries might provide more complex
1245 /// patterns like regular expressions.
1247 /// # Iterator behavior
1249 /// The returned iterator will be double ended if the pattern allows a
1250 /// reverse search and forward/reverse search yields the same elements.
1251 /// This is true for, eg, `char` but not
1254 /// If the pattern allows a reverse search but its results might differ
1255 /// from a forward search, `rsplit()` can be used.
1259 /// Simple patterns:
1262 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1263 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1265 /// let v: Vec<&str> = "".split('X').collect();
1266 /// assert_eq!(v, [""]);
1268 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1269 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1271 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1272 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1274 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1275 /// assert_eq!(v, ["abc", "def", "ghi"]);
1277 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1278 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1281 /// A more complex pattern, using a closure:
1284 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1285 /// assert_eq!(v, ["abc", "def", "ghi"]);
1288 /// If a string contains multiple contiguous separators, you will end up
1289 /// with empty strings in the output:
1292 /// let x = "||||a||b|c".to_string();
1293 /// let d: Vec<_> = x.split('|').collect();
1295 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1298 /// This can lead to possibly surprising behavior when whitespace is used
1299 /// as the separator. This code is correct:
1302 /// let x = " a b c".to_string();
1303 /// let d: Vec<_> = x.split(' ').collect();
1305 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1308 /// It does _not_ give you:
1311 /// assert_eq!(d, &["a", "b", "c"]);
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1315 core_str::StrExt::split(self, pat)
1318 /// An iterator over substrings of `self`, separated by characters
1319 /// matched by a pattern and yielded in reverse order.
1321 /// The pattern can be a simple `&str`, `char`, or a closure that
1322 /// determines the split.
1323 /// Additional libraries might provide more complex patterns like
1324 /// regular expressions.
1326 /// # Iterator behavior
1328 /// The returned iterator requires that the pattern supports a
1330 /// and it will be double ended if a forward/reverse search yields
1331 /// the same elements.
1333 /// For iterating from the front, `split()` can be used.
1337 /// Simple patterns:
1340 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1341 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1343 /// let v: Vec<&str> = "".rsplit('X').collect();
1344 /// assert_eq!(v, [""]);
1346 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1347 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1349 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1350 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1353 /// A more complex pattern, using a closure:
1356 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1357 /// assert_eq!(v, ["ghi", "def", "abc"]);
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1361 where P::Searcher: ReverseSearcher<'a>
1363 core_str::StrExt::rsplit(self, pat)
1366 /// An iterator over substrings of `self`, separated by characters
1367 /// matched by a pattern.
1369 /// The pattern can be a simple `&str`, `char`, or a closure that
1370 /// determines the split.
1371 /// Additional libraries might provide more complex patterns
1372 /// like regular expressions.
1374 /// Equivalent to `split`, except that the trailing substring
1375 /// is skipped if empty.
1377 /// This method can be used for string data that is _terminated_,
1378 /// rather than _separated_ by a pattern.
1380 /// # Iterator behavior
1382 /// The returned iterator will be double ended if the pattern allows a
1384 /// and forward/reverse search yields the same elements. This is true
1385 /// for, eg, `char` but not for `&str`.
1387 /// If the pattern allows a reverse search but its results might differ
1388 /// from a forward search, `rsplit_terminator()` can be used.
1393 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1394 /// assert_eq!(v, ["A", "B"]);
1396 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1397 /// assert_eq!(v, ["A", "", "B", ""]);
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1401 core_str::StrExt::split_terminator(self, pat)
1404 /// An iterator over substrings of `self`, separated by characters
1405 /// matched by a pattern and yielded in reverse order.
1407 /// The pattern can be a simple `&str`, `char`, or a closure that
1408 /// determines the split.
1409 /// Additional libraries might provide more complex patterns like
1410 /// regular expressions.
1412 /// Equivalent to `split`, except that the trailing substring is
1413 /// skipped if empty.
1415 /// This method can be used for string data that is _terminated_,
1416 /// rather than _separated_ by a pattern.
1418 /// # Iterator behavior
1420 /// The returned iterator requires that the pattern supports a
1421 /// reverse search, and it will be double ended if a forward/reverse
1422 /// search yields the same elements.
1424 /// For iterating from the front, `split_terminator()` can be used.
1429 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1430 /// assert_eq!(v, ["B", "A"]);
1432 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1433 /// assert_eq!(v, ["", "B", "", "A"]);
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1437 where P::Searcher: ReverseSearcher<'a>
1439 core_str::StrExt::rsplit_terminator(self, pat)
1442 /// An iterator over substrings of `self`, separated by a pattern,
1443 /// restricted to returning
1444 /// at most `count` items.
1446 /// The last element returned, if any, will contain the remainder of the
1448 /// The pattern can be a simple `&str`, `char`, or a closure that
1449 /// determines the split.
1450 /// Additional libraries might provide more complex patterns like
1451 /// regular expressions.
1453 /// # Iterator behavior
1455 /// The returned iterator will not be double ended, because it is
1456 /// not efficient to support.
1458 /// If the pattern allows a reverse search, `rsplitn()` can be used.
1462 /// Simple patterns:
1465 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1466 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1468 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1469 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1471 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1472 /// assert_eq!(v, ["abcXdef"]);
1474 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1475 /// assert_eq!(v, [""]);
1478 /// A more complex pattern, using a closure:
1481 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1482 /// assert_eq!(v, ["abc", "defXghi"]);
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 pub fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1486 core_str::StrExt::splitn(self, count, pat)
1489 /// An iterator over substrings of `self`, separated by a pattern,
1490 /// starting from the end of the string, restricted to returning
1491 /// at most `count` items.
1493 /// The last element returned, if any, will contain the remainder of the
1496 /// The pattern can be a simple `&str`, `char`, or a closure that
1497 /// determines the split.
1498 /// Additional libraries might provide more complex patterns like
1499 /// regular expressions.
1501 /// # Iterator behavior
1503 /// The returned iterator will not be double ended, because it is not
1504 /// efficient to support.
1506 /// `splitn()` can be used for splitting from the front.
1510 /// Simple patterns:
1513 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1514 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1516 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1517 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1519 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1520 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1523 /// A more complex pattern, using a closure:
1526 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1527 /// assert_eq!(v, ["ghi", "abc1def"]);
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1531 where P::Searcher: ReverseSearcher<'a>
1533 core_str::StrExt::rsplitn(self, count, pat)
1536 /// An iterator over the matches of a pattern within `self`.
1538 /// The pattern can be a simple `&str`, `char`, or a closure that
1539 /// determines the split.
1540 /// Additional libraries might provide more complex patterns like
1541 /// regular expressions.
1543 /// # Iterator behavior
1545 /// The returned iterator will be double ended if the pattern allows
1546 /// a reverse search
1547 /// and forward/reverse search yields the same elements. This is true
1548 /// for, eg, `char` but not
1551 /// If the pattern allows a reverse search but its results might differ
1552 /// from a forward search, `rmatches()` can be used.
1557 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1558 /// assert_eq!(v, ["abc", "abc", "abc"]);
1560 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1561 /// assert_eq!(v, ["1", "2", "3"]);
1563 #[stable(feature = "str_matches", since = "1.2.0")]
1564 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1565 core_str::StrExt::matches(self, pat)
1568 /// An iterator over the matches of a pattern within `self`, yielded in
1571 /// The pattern can be a simple `&str`, `char`, or a closure that
1572 /// determines the split.
1573 /// Additional libraries might provide more complex patterns like
1574 /// regular expressions.
1576 /// # Iterator behavior
1578 /// The returned iterator requires that the pattern supports a
1580 /// and it will be double ended if a forward/reverse search yields
1581 /// the same elements.
1583 /// For iterating from the front, `matches()` can be used.
1588 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1589 /// assert_eq!(v, ["abc", "abc", "abc"]);
1591 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1592 /// assert_eq!(v, ["3", "2", "1"]);
1594 #[stable(feature = "str_matches", since = "1.2.0")]
1595 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1596 where P::Searcher: ReverseSearcher<'a>
1598 core_str::StrExt::rmatches(self, pat)
1601 /// An iterator over the start and end indices of the disjoint matches
1602 /// of a pattern within `self`.
1604 /// For matches of `pat` within `self` that overlap, only the indices
1605 /// corresponding to the first
1606 /// match are returned.
1608 /// The pattern can be a simple `&str`, `char`, or a closure that
1611 /// Additional libraries might provide more complex patterns like
1612 /// regular expressions.
1614 /// # Iterator behavior
1616 /// The returned iterator will be double ended if the pattern allows a
1618 /// and forward/reverse search yields the same elements. This is true for,
1619 /// eg, `char` but not
1622 /// If the pattern allows a reverse search but its results might differ
1623 /// from a forward search, `rmatch_indices()` can be used.
1628 /// #![feature(str_match_indices)]
1630 /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
1631 /// assert_eq!(v, [(0, 3), (6, 9), (12, 15)]);
1633 /// let v: Vec<(usize, usize)> = "1abcabc2".match_indices("abc").collect();
1634 /// assert_eq!(v, [(1, 4), (4, 7)]);
1636 /// let v: Vec<(usize, usize)> = "ababa".match_indices("aba").collect();
1637 /// assert_eq!(v, [(0, 3)]); // only the first `aba`
1639 #[unstable(feature = "str_match_indices",
1640 reason = "might have its iterator type changed")]
1641 // NB: Right now MatchIndices yields `(usize, usize)`, but it would
1642 // be more consistent with `matches` and `char_indices` to return `(usize, &str)`
1643 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1644 core_str::StrExt::match_indices(self, pat)
1647 /// An iterator over the start and end indices of the disjoint matches of
1648 /// a pattern within
1649 /// `self`, yielded in reverse order.
1651 /// For matches of `pat` within `self` that overlap, only the indices
1652 /// corresponding to the last
1653 /// match are returned.
1655 /// The pattern can be a simple `&str`, `char`, or a closure that
1658 /// Additional libraries might provide more complex patterns like
1659 /// regular expressions.
1661 /// # Iterator behavior
1663 /// The returned iterator requires that the pattern supports a
1665 /// and it will be double ended if a forward/reverse search yields
1666 /// the same elements.
1668 /// For iterating from the front, `match_indices()` can be used.
1673 /// #![feature(str_match_indices)]
1675 /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1676 /// assert_eq!(v, [(12, 15), (6, 9), (0, 3)]);
1678 /// let v: Vec<(usize, usize)> = "1abcabc2".rmatch_indices("abc").collect();
1679 /// assert_eq!(v, [(4, 7), (1, 4)]);
1681 /// let v: Vec<(usize, usize)> = "ababa".rmatch_indices("aba").collect();
1682 /// assert_eq!(v, [(2, 5)]); // only the last `aba`
1684 #[unstable(feature = "str_match_indices",
1685 reason = "might have its iterator type changed")]
1686 // NB: Right now RMatchIndices yields `(usize, usize)`, but it would
1687 // be more consistent with `rmatches` and `char_indices` to return `(usize, &str)`
1688 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1689 where P::Searcher: ReverseSearcher<'a>
1691 core_str::StrExt::rmatch_indices(self, pat)
1694 /// Returns the byte offset of an inner slice relative to an enclosing
1699 /// Panics if `inner` is not a direct slice contained within self.
1704 /// #![feature(subslice_offset)]
1706 /// let string = "a\nb\nc";
1707 /// let lines: Vec<&str> = string.lines().collect();
1709 /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
1710 /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
1711 /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
1713 #[unstable(feature = "subslice_offset",
1714 reason = "awaiting convention about comparability of arbitrary slices")]
1715 #[deprecated(since = "1.3.0",
1716 reason = "replaced with other pattern-related methods")]
1717 pub fn subslice_offset(&self, inner: &str) -> usize {
1718 core_str::StrExt::subslice_offset(self, inner)
1721 /// Returns a `&str` with leading and trailing whitespace removed.
1726 /// let s = " Hello\tworld\t";
1727 /// assert_eq!(s.trim(), "Hello\tworld");
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 pub fn trim(&self) -> &str {
1731 UnicodeStr::trim(self)
1734 /// Returns a `&str` with leading whitespace removed.
1739 /// let s = " Hello\tworld\t";
1740 /// assert_eq!(s.trim_left(), "Hello\tworld\t");
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 pub fn trim_left(&self) -> &str {
1744 UnicodeStr::trim_left(self)
1747 /// Returns a `&str` with trailing whitespace removed.
1752 /// let s = " Hello\tworld\t";
1753 /// assert_eq!(s.trim_right(), " Hello\tworld");
1755 #[stable(feature = "rust1", since = "1.0.0")]
1756 pub fn trim_right(&self) -> &str {
1757 UnicodeStr::trim_right(self)
1760 /// Returns a string with all pre- and suffixes that match a pattern
1761 /// repeatedly removed.
1763 /// The pattern can be a simple `char`, or a closure that determines
1768 /// Simple patterns:
1771 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1772 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1774 /// let x: &[_] = &['1', '2'];
1775 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1778 /// A more complex pattern, using a closure:
1781 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1785 where P::Searcher: DoubleEndedSearcher<'a>
1787 core_str::StrExt::trim_matches(self, pat)
1790 /// Returns a string with all prefixes that match a pattern
1791 /// repeatedly removed.
1793 /// The pattern can be a simple `&str`, `char`, or a closure that
1794 /// determines the split.
1799 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1800 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1802 /// let x: &[_] = &['1', '2'];
1803 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1805 #[stable(feature = "rust1", since = "1.0.0")]
1806 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1807 core_str::StrExt::trim_left_matches(self, pat)
1810 /// Returns a string with all suffixes that match a pattern
1811 /// repeatedly removed.
1813 /// The pattern can be a simple `&str`, `char`, or a closure that
1814 /// determines the split.
1818 /// Simple patterns:
1821 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1822 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1824 /// let x: &[_] = &['1', '2'];
1825 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1828 /// A more complex pattern, using a closure:
1831 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1833 #[stable(feature = "rust1", since = "1.0.0")]
1834 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1835 where P::Searcher: ReverseSearcher<'a>
1837 core_str::StrExt::trim_right_matches(self, pat)
1840 /// Parses `self` into the specified type.
1844 /// Will return `Err` if it's not possible to parse `self` into the type.
1849 /// assert_eq!("4".parse::<u32>(), Ok(4));
1855 /// assert!("j".parse::<u32>().is_err());
1858 #[stable(feature = "rust1", since = "1.0.0")]
1859 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1860 core_str::StrExt::parse(self)
1863 /// Replaces all occurrences of one string with another.
1865 /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a
1866 /// second `&str` to
1867 /// replace it with. If the original `&str` isn't found, no change occurs.
1872 /// let s = "this is old";
1874 /// assert_eq!(s.replace("old", "new"), "this is new");
1877 /// When a `&str` isn't found:
1880 /// let s = "this is old";
1881 /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
1883 #[stable(feature = "rust1", since = "1.0.0")]
1884 pub fn replace(&self, from: &str, to: &str) -> String {
1885 let mut result = String::new();
1886 let mut last_end = 0;
1887 for (start, end) in self.match_indices(from) {
1888 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1889 result.push_str(to);
1892 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1896 /// Returns the lowercase equivalent of this string.
1901 /// let s = "HELLO";
1902 /// assert_eq!(s.to_lowercase(), "hello");
1904 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1905 pub fn to_lowercase(&self) -> String {
1906 let mut s = String::with_capacity(self.len());
1907 for (i, c) in self[..].char_indices() {
1909 // Σ maps to σ, except at the end of a word where it maps to ς.
1910 // This is the only conditional (contextual) but language-independent mapping
1911 // in `SpecialCasing.txt`,
1912 // so hard-code it rather than have a generic "condition" mechanim.
1913 // See https://github.com/rust-lang/rust/issues/26035
1914 map_uppercase_sigma(self, i, &mut s)
1916 s.extend(c.to_lowercase());
1921 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1922 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1923 // for the definition of `Final_Sigma`.
1924 debug_assert!('Σ'.len_utf8() == 2);
1926 case_ignoreable_then_cased(from[..i].chars().rev()) &&
1927 !case_ignoreable_then_cased(from[i + 2..].chars());
1928 to.push_str(if is_word_final { "ς" } else { "σ" });
1931 fn case_ignoreable_then_cased<I: Iterator<Item=char>>(iter: I) -> bool {
1932 use rustc_unicode::derived_property::{Cased, Case_Ignorable};
1933 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1934 Some(c) => Cased(c),
1940 /// Returns the uppercase equivalent of this string.
1945 /// let s = "hello";
1946 /// assert_eq!(s.to_uppercase(), "HELLO");
1948 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1949 pub fn to_uppercase(&self) -> String {
1950 let mut s = String::with_capacity(self.len());
1951 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1955 /// Escapes each char in `s` with `char::escape_default`.
1956 #[unstable(feature = "str_escape",
1957 reason = "return type may change to be an iterator")]
1958 pub fn escape_default(&self) -> String {
1959 self.chars().flat_map(|c| c.escape_default()).collect()
1962 /// Escapes each char in `s` with `char::escape_unicode`.
1963 #[unstable(feature = "str_escape",
1964 reason = "return type may change to be an iterator")]
1965 pub fn escape_unicode(&self) -> String {
1966 self.chars().flat_map(|c| c.escape_unicode()).collect()
1969 /// Converts the `Box<str>` into a `String` without copying or allocating.
1970 #[unstable(feature = "box_str",
1971 reason = "recently added, matches RFC")]
1972 pub fn into_string(self: Box<str>) -> String {
1974 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1975 String::from_utf8_unchecked(slice.into_vec())