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 /// Returns a raw pointer to the `&str`'s buffer.
484 /// The caller must ensure that the string outlives this pointer, and
486 /// reallocated (e.g. by pushing to the string).
492 /// let p = s.as_ptr();
494 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn as_ptr(&self) -> *const u8 {
497 core_str::StrExt::as_ptr(self)
500 /// Takes a bytewise slice from a string.
502 /// Returns the substring from [`begin`..`end`).
506 /// Caller must check both UTF-8 sequence boundaries and the boundaries
507 /// of the entire slice as well.
512 /// let s = "Löwe 老虎 Léopard";
515 /// assert_eq!(s.slice_unchecked(0, 21), "Löwe 老虎 Léopard");
518 #[stable(feature = "rust1", since = "1.0.0")]
520 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
521 core_str::StrExt::slice_unchecked(self, begin, end)
524 /// Takes a bytewise mutable slice from a string.
526 /// Same as `slice_unchecked`, but works with `&mut str` instead of `&str`.
527 #[unstable(feature = "str_slice_mut", reason = "recently added")]
529 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
530 core_str::StrExt::slice_mut_unchecked(self, begin, end)
533 /// Returns a slice of the string from the range [`begin`..`end`) where indices
534 /// are counted in code points.
536 /// That is, start at the `begin`-th code point of the string and continue
537 /// to the `end`-th code point. This does not detect or handle edge cases
538 /// such as leaving a combining character as the first `char` of the
541 /// Due to the design of UTF-8, this operation is `O(end)`. Use slicing
542 /// syntax if you want to use `O(1)` byte indices instead.
546 /// Panics if `begin` > `end` or the either `begin` or `end` are beyond the
547 /// last character of the string.
552 /// #![feature(slice_chars)]
554 /// let s = "Löwe 老虎 Léopard";
556 /// assert_eq!(s.slice_chars(0, 4), "Löwe");
557 /// assert_eq!(s.slice_chars(5, 7), "老虎");
559 #[unstable(feature = "slice_chars",
560 reason = "may have yet to prove its worth")]
561 #[deprecated(since = "1.3.0",
562 reason = "can be implemented with char_indices and \
563 hasn't seen enough use to justify inclusion")]
565 pub fn slice_chars(&self, begin: usize, end: usize) -> &str {
566 core_str::StrExt::slice_chars(self, begin, end)
569 /// Given a byte position, return the next code point and its index.
571 /// This can be used to iterate over the Unicode code points of a string.
575 /// If `i` is greater than or equal to the length of the string.
576 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
580 /// This example manually iterates through the code points of a string;
581 /// this should normally be
582 /// done by `.chars()` or `.char_indices()`.
585 /// #![feature(str_char, core)]
587 /// use std::str::CharRange;
589 /// let s = "中华Việt Nam";
591 /// while i < s.len() {
592 /// let CharRange {ch, next} = s.char_range_at(i);
593 /// println!("{}: {}", i, ch);
614 #[unstable(feature = "str_char",
615 reason = "often replaced by char_indices, this method may \
616 be removed in favor of just char_at() or eventually \
617 removed altogether")]
619 pub fn char_range_at(&self, start: usize) -> CharRange {
620 core_str::StrExt::char_range_at(self, start)
623 /// Given a byte position, return the previous `char` and its position.
625 /// This function can be used to iterate over a Unicode code points in reverse.
627 /// Note that Unicode has many features, such as combining marks, ligatures,
628 /// and direction marks, that need to be taken into account to correctly reverse a string.
630 /// Returns 0 for next index if called on start index 0.
634 /// If `i` is greater than the length of the string.
635 /// If `i` is not an index following a valid UTF-8 sequence.
639 /// This example manually iterates through the code points of a string;
640 /// this should normally be
641 /// done by `.chars().rev()` or `.char_indices()`.
644 /// #![feature(str_char, core)]
646 /// use std::str::CharRange;
648 /// let s = "中华Việt Nam";
649 /// let mut i = s.len();
651 /// let CharRange {ch, next} = s.char_range_at_reverse(i);
652 /// println!("{}: {}", i, ch);
673 #[unstable(feature = "str_char",
674 reason = "often replaced by char_indices, this method may \
675 be removed in favor of just char_at_reverse() or \
676 eventually removed altogether")]
678 pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
679 core_str::StrExt::char_range_at_reverse(self, start)
682 /// Given a byte position, return the `char` at that position.
686 /// If `i` is greater than or equal to the length of the string.
687 /// If `i` is not the index of the beginning of a valid UTF-8 sequence.
692 /// #![feature(str_char)]
695 /// assert_eq!(s.char_at(1), 'b');
696 /// assert_eq!(s.char_at(2), 'π');
697 /// assert_eq!(s.char_at(4), 'c');
699 #[unstable(feature = "str_char",
700 reason = "frequently replaced by the chars() iterator, this \
701 method may be removed or possibly renamed in the \
702 future; it is normally replaced by chars/char_indices \
703 iterators or by getting the first char from a \
706 pub fn char_at(&self, i: usize) -> char {
707 core_str::StrExt::char_at(self, i)
710 /// Given a byte position, return the `char` at that position, counting
715 /// If `i` is greater than the length of the string.
716 /// If `i` is not an index following a valid UTF-8 sequence.
721 /// #![feature(str_char)]
724 /// assert_eq!(s.char_at_reverse(1), 'a');
725 /// assert_eq!(s.char_at_reverse(2), 'b');
726 /// assert_eq!(s.char_at_reverse(3), 'π');
728 #[unstable(feature = "str_char",
729 reason = "see char_at for more details, but reverse semantics \
730 are also somewhat unclear, especially with which \
731 cases generate panics")]
733 pub fn char_at_reverse(&self, i: usize) -> char {
734 core_str::StrExt::char_at_reverse(self, i)
737 /// Retrieves the first code point from a `&str` and returns it.
739 /// Note that a single Unicode character (grapheme cluster)
740 /// can be composed of multiple `char`s.
742 /// This does not allocate a new string; instead, it returns a slice that
743 /// points one code point beyond the code point that was shifted.
745 /// `None` is returned if the slice is empty.
750 /// #![feature(str_char)]
752 /// let s = "Łódź"; // \u{141}o\u{301}dz\u{301}
753 /// let (c, s1) = s.slice_shift_char().unwrap();
755 /// assert_eq!(c, 'Ł');
756 /// assert_eq!(s1, "ódź");
758 /// let (c, s2) = s1.slice_shift_char().unwrap();
760 /// assert_eq!(c, 'o');
761 /// assert_eq!(s2, "\u{301}dz\u{301}");
763 #[unstable(feature = "str_char",
764 reason = "awaiting conventions about shifting and slices and \
765 may not be warranted with the existence of the chars \
766 and/or char_indices iterators")]
768 pub fn slice_shift_char(&self) -> Option<(char, &str)> {
769 core_str::StrExt::slice_shift_char(self)
772 /// Divide one string slice into two at an index.
774 /// The index `mid` is a byte offset from the start of the string
775 /// that must be on a `char` boundary.
777 /// Return slices `&self[..mid]` and `&self[mid..]`.
781 /// Panics if `mid` is beyond the last code point of the string,
782 /// or if it is not on a `char` boundary.
786 /// #![feature(str_split_at)]
788 /// let s = "Löwe 老虎 Léopard";
789 /// let first_space = s.find(' ').unwrap_or(s.len());
790 /// let (a, b) = s.split_at(first_space);
792 /// assert_eq!(a, "Löwe");
793 /// assert_eq!(b, " 老虎 Léopard");
796 #[unstable(feature = "str_split_at", reason = "recently added")]
797 pub fn split_at(&self, mid: usize) -> (&str, &str) {
798 core_str::StrExt::split_at(self, mid)
801 /// Divide one mutable string slice into two at an index.
803 #[unstable(feature = "str_split_at", reason = "recently added")]
804 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
805 core_str::StrExt::split_at_mut(self, mid)
808 /// An iterator over the code points of `self`.
810 /// In Unicode relationship between code points and characters is complex.
811 /// A single character may be composed of multiple code points
812 /// (e.g. diacritical marks added to a letter), and a single code point
813 /// (e.g. Hangul syllable) may contain multiple characters.
815 /// For iteration over human-readable characters a grapheme cluster iterator
816 /// may be more appropriate. See the [unicode-segmentation crate][1].
818 /// [1]: https://crates.io/crates/unicode-segmentation
823 /// let v: Vec<char> = "ASCII żółć 🇨🇭 한".chars().collect();
825 /// assert_eq!(v, ['A', 'S', 'C', 'I', 'I', ' ',
826 /// 'z', '\u{307}', 'o', '\u{301}', 'ł', 'c', '\u{301}', ' ',
827 /// '\u{1f1e8}', '\u{1f1ed}', ' ', '한']);
829 #[stable(feature = "rust1", since = "1.0.0")]
831 pub fn chars(&self) -> Chars {
832 core_str::StrExt::chars(self)
835 /// An iterator over the `char`s of `self` and their byte offsets.
840 /// let v: Vec<(usize, char)> = "A🇨🇭".char_indices().collect();
841 /// let b = vec![(0, 'A'), (1, '\u{1f1e8}'), (5, '\u{1f1ed}')];
843 /// assert_eq!(v, b);
845 #[stable(feature = "rust1", since = "1.0.0")]
847 pub fn char_indices(&self) -> CharIndices {
848 core_str::StrExt::char_indices(self)
851 /// An iterator over the bytes of `self`.
856 /// let v: Vec<u8> = "bors".bytes().collect();
858 /// assert_eq!(v, b"bors".to_vec());
860 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn bytes(&self) -> Bytes {
863 core_str::StrExt::bytes(self)
866 /// An iterator over the non-empty substrings of `self` which contain no whitespace,
867 /// and which are separated by any amount of whitespace.
872 /// let some_words = " Mary had\ta\u{2009}little \n\t lamb";
873 /// let v: Vec<&str> = some_words.split_whitespace().collect();
875 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
877 #[stable(feature = "split_whitespace", since = "1.1.0")]
879 pub fn split_whitespace(&self) -> SplitWhitespace {
880 UnicodeStr::split_whitespace(self)
883 /// An iterator over the non-empty substrings of `self` which contain no whitespace,
884 /// and which are separated by any amount of whitespace.
889 /// #![feature(str_words)]
890 /// #![allow(deprecated)]
892 /// let some_words = " Mary had\ta\u{2009}little \n\t lamb";
893 /// let v: Vec<&str> = some_words.words().collect();
895 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
897 #[deprecated(reason = "words() will be removed. Use split_whitespace() instead",
899 #[unstable(feature = "str_words",
900 reason = "the precise algorithm to use is unclear")]
903 pub fn words(&self) -> Words {
904 UnicodeStr::words(self)
907 /// An iterator over the lines of a string, separated by `\n`.
909 /// This does not include the empty string after a trailing `\n`.
914 /// let four_lines = "foo\nbar\n\nbaz";
915 /// let v: Vec<&str> = four_lines.lines().collect();
917 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
920 /// Leaving off the trailing character:
923 /// let four_lines = "foo\nbar\n\nbaz\n";
924 /// let v: Vec<&str> = four_lines.lines().collect();
926 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
928 #[stable(feature = "rust1", since = "1.0.0")]
930 pub fn lines(&self) -> Lines {
931 core_str::StrExt::lines(self)
934 /// An iterator over the lines of a string, separated by either
937 /// As with `.lines()`, this does not include an empty trailing line.
942 /// let four_lines = "foo\r\nbar\n\r\nbaz";
943 /// let v: Vec<&str> = four_lines.lines_any().collect();
945 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
948 /// Leaving off the trailing character:
951 /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
952 /// let v: Vec<&str> = four_lines.lines_any().collect();
954 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
956 #[stable(feature = "rust1", since = "1.0.0")]
958 pub fn lines_any(&self) -> LinesAny {
959 core_str::StrExt::lines_any(self)
962 /// Returns an iterator over the string in Unicode Normalization Form D
963 /// (canonical decomposition).
965 #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
968 #[unstable(feature = "unicode",
969 reason = "this functionality may be replaced with a more generic \
970 unicode crate on crates.io")]
971 pub fn nfd_chars(&self) -> Decompositions {
973 iter: self[..].chars(),
980 /// Returns an iterator over the string in Unicode Normalization Form KD
981 /// (compatibility decomposition).
983 #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
986 #[unstable(feature = "unicode",
987 reason = "this functionality may be replaced with a more generic \
988 unicode crate on crates.io")]
989 pub fn nfkd_chars(&self) -> Decompositions {
991 iter: self[..].chars(),
998 /// An Iterator over the string in Unicode Normalization Form C
999 /// (canonical decomposition followed by canonical composition).
1000 #[allow(deprecated)]
1001 #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
1004 #[unstable(feature = "unicode",
1005 reason = "this functionality may be replaced with a more generic \
1006 unicode crate on crates.io")]
1007 pub fn nfc_chars(&self) -> Recompositions {
1009 iter: self.nfd_chars(),
1011 buffer: VecDeque::new(),
1017 /// An Iterator over the string in Unicode Normalization Form KC
1018 /// (compatibility decomposition followed by canonical composition).
1019 #[allow(deprecated)]
1020 #[deprecated(reason = "use the crates.io `unicode-normalization` library instead",
1023 #[unstable(feature = "unicode",
1024 reason = "this functionality may be replaced with a more generic \
1025 unicode crate on crates.io")]
1026 pub fn nfkc_chars(&self) -> Recompositions {
1028 iter: self.nfkd_chars(),
1030 buffer: VecDeque::new(),
1036 /// Returns an iterator over the [grapheme clusters][graphemes] of `self`.
1038 /// [graphemes]: http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
1040 /// If `is_extended` is true, the iterator is over the
1041 /// *extended grapheme clusters*;
1042 /// otherwise, the iterator is over the *legacy grapheme clusters*.
1043 /// [UAX#29](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
1044 /// recommends extended grapheme cluster boundaries for general processing.
1049 /// #![feature(unicode, core)]
1051 /// let gr1 = "a\u{310}e\u{301}o\u{308}\u{332}".graphemes(true).collect::<Vec<&str>>();
1052 /// let b: &[_] = &["a\u{310}", "e\u{301}", "o\u{308}\u{332}"];
1054 /// assert_eq!(&gr1[..], b);
1056 /// let gr2 = "a\r\nb🇷🇺🇸🇹".graphemes(true).collect::<Vec<&str>>();
1057 /// let b: &[_] = &["a", "\r\n", "b", "🇷🇺🇸🇹"];
1059 /// assert_eq!(&gr2[..], b);
1061 #[deprecated(reason = "use the crates.io `unicode-segmentation` library instead",
1063 #[unstable(feature = "unicode",
1064 reason = "this functionality may only be provided by libunicode")]
1065 pub fn graphemes(&self, is_extended: bool) -> Graphemes {
1066 UnicodeStr::graphemes(self, is_extended)
1069 /// Returns an iterator over the grapheme clusters of `self` and their
1070 /// byte offsets. See
1071 /// `graphemes()` for more information.
1076 /// #![feature(unicode, core)]
1078 /// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(usize, &str)>>();
1079 /// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
1081 /// assert_eq!(&gr_inds[..], b);
1083 #[deprecated(reason = "use the crates.io `unicode-segmentation` library instead",
1085 #[unstable(feature = "unicode",
1086 reason = "this functionality may only be provided by libunicode")]
1087 pub fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices {
1088 UnicodeStr::grapheme_indices(self, is_extended)
1091 /// Returns an iterator of `u16` over the string encoded as UTF-16.
1092 #[unstable(feature = "str_utf16",
1093 reason = "this functionality may only be provided by libunicode")]
1094 pub fn utf16_units(&self) -> Utf16Units {
1095 Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
1098 /// Returns `true` if `self` contains another `&str`.
1103 /// assert!("bananas".contains("nana"));
1105 /// assert!(!"bananas".contains("foobar"));
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1109 core_str::StrExt::contains(self, pat)
1112 /// Returns `true` if the given `&str` is a prefix of the string.
1117 /// assert!("banana".starts_with("ba"));
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1121 core_str::StrExt::starts_with(self, pat)
1124 /// Returns true if the given `&str` is a suffix of the string.
1129 /// assert!("banana".ends_with("nana"));
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
1133 where P::Searcher: ReverseSearcher<'a>
1135 core_str::StrExt::ends_with(self, pat)
1138 /// Returns the byte index of the first character of `self` that matches
1139 /// the pattern, if it
1142 /// Returns `None` if it doesn't exist.
1144 /// The pattern can be a simple `&str`, `char`, or a closure that
1150 /// Simple patterns:
1153 /// let s = "Löwe 老虎 Léopard";
1155 /// assert_eq!(s.find('L'), Some(0));
1156 /// assert_eq!(s.find('é'), Some(14));
1157 /// assert_eq!(s.find("Léopard"), Some(13));
1161 /// More complex patterns with closures:
1164 /// let s = "Löwe 老虎 Léopard";
1166 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1167 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1170 /// Not finding the pattern:
1173 /// let s = "Löwe 老虎 Léopard";
1174 /// let x: &[_] = &['1', '2'];
1176 /// assert_eq!(s.find(x), None);
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1180 core_str::StrExt::find(self, pat)
1183 /// Returns the byte index of the last character of `self` that
1184 /// matches the pattern, if it
1187 /// Returns `None` if it doesn't exist.
1189 /// The pattern can be a simple `&str`, `char`,
1190 /// or a closure that determines the split.
1194 /// Simple patterns:
1197 /// let s = "Löwe 老虎 Léopard";
1199 /// assert_eq!(s.rfind('L'), Some(13));
1200 /// assert_eq!(s.rfind('é'), Some(14));
1203 /// More complex patterns with closures:
1206 /// let s = "Löwe 老虎 Léopard";
1208 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1209 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1212 /// Not finding the pattern:
1215 /// let s = "Löwe 老虎 Léopard";
1216 /// let x: &[_] = &['1', '2'];
1218 /// assert_eq!(s.rfind(x), None);
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1222 where P::Searcher: ReverseSearcher<'a>
1224 core_str::StrExt::rfind(self, pat)
1227 /// An iterator over substrings of `self`, separated by characters
1228 /// matched by a pattern.
1230 /// The pattern can be a simple `&str`, `char`, or a closure that
1231 /// determines the split. Additional libraries might provide more complex
1232 /// patterns like regular expressions.
1234 /// # Iterator behavior
1236 /// The returned iterator will be double ended if the pattern allows a
1237 /// reverse search and forward/reverse search yields the same elements.
1238 /// This is true for, eg, `char` but not
1241 /// If the pattern allows a reverse search but its results might differ
1242 /// from a forward search, `rsplit()` can be used.
1246 /// Simple patterns:
1249 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1250 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1252 /// let v: Vec<&str> = "".split('X').collect();
1253 /// assert_eq!(v, [""]);
1255 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1256 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1258 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1259 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1261 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1262 /// assert_eq!(v, ["abc", "def", "ghi"]);
1264 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1265 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1268 /// A more complex pattern, using a closure:
1271 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1272 /// assert_eq!(v, ["abc", "def", "ghi"]);
1275 /// If a string contains multiple contiguous separators, you will end up
1276 /// with empty strings in the output:
1279 /// let x = "||||a||b|c".to_string();
1280 /// let d: Vec<_> = x.split('|').collect();
1282 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1285 /// This can lead to possibly surprising behavior when whitespace is used
1286 /// as the separator. This code is correct:
1289 /// let x = " a b c".to_string();
1290 /// let d: Vec<_> = x.split(' ').collect();
1292 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1295 /// It does _not_ give you:
1298 /// assert_eq!(d, &["a", "b", "c"]);
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1302 core_str::StrExt::split(self, pat)
1305 /// An iterator over substrings of `self`, separated by characters
1306 /// matched by a pattern and yielded in reverse order.
1308 /// The pattern can be a simple `&str`, `char`, or a closure that
1309 /// determines the split.
1310 /// Additional libraries might provide more complex patterns like
1311 /// regular expressions.
1313 /// # Iterator behavior
1315 /// The returned iterator requires that the pattern supports a
1317 /// and it will be double ended if a forward/reverse search yields
1318 /// the same elements.
1320 /// For iterating from the front, `split()` can be used.
1324 /// Simple patterns:
1327 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1328 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1330 /// let v: Vec<&str> = "".rsplit('X').collect();
1331 /// assert_eq!(v, [""]);
1333 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1334 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1336 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1337 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1340 /// A more complex pattern, using a closure:
1343 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1344 /// assert_eq!(v, ["ghi", "def", "abc"]);
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1348 where P::Searcher: ReverseSearcher<'a>
1350 core_str::StrExt::rsplit(self, pat)
1353 /// An iterator over substrings of `self`, separated by characters
1354 /// matched by a pattern.
1356 /// The pattern can be a simple `&str`, `char`, or a closure that
1357 /// determines the split.
1358 /// Additional libraries might provide more complex patterns
1359 /// like regular expressions.
1361 /// Equivalent to `split`, except that the trailing substring
1362 /// is skipped if empty.
1364 /// This method can be used for string data that is _terminated_,
1365 /// rather than _separated_ by a pattern.
1367 /// # Iterator behavior
1369 /// The returned iterator will be double ended if the pattern allows a
1371 /// and forward/reverse search yields the same elements. This is true
1372 /// for, eg, `char` but not for `&str`.
1374 /// If the pattern allows a reverse search but its results might differ
1375 /// from a forward search, `rsplit_terminator()` can be used.
1380 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1381 /// assert_eq!(v, ["A", "B"]);
1383 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1384 /// assert_eq!(v, ["A", "", "B", ""]);
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1388 core_str::StrExt::split_terminator(self, pat)
1391 /// An iterator over substrings of `self`, separated by characters
1392 /// matched by a pattern and yielded in reverse order.
1394 /// The pattern can be a simple `&str`, `char`, or a closure that
1395 /// determines the split.
1396 /// Additional libraries might provide more complex patterns like
1397 /// regular expressions.
1399 /// Equivalent to `split`, except that the trailing substring is
1400 /// skipped if empty.
1402 /// This method can be used for string data that is _terminated_,
1403 /// rather than _separated_ by a pattern.
1405 /// # Iterator behavior
1407 /// The returned iterator requires that the pattern supports a
1408 /// reverse search, and it will be double ended if a forward/reverse
1409 /// search yields the same elements.
1411 /// For iterating from the front, `split_terminator()` can be used.
1416 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1417 /// assert_eq!(v, ["B", "A"]);
1419 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1420 /// assert_eq!(v, ["", "B", "", "A"]);
1422 #[stable(feature = "rust1", since = "1.0.0")]
1423 pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1424 where P::Searcher: ReverseSearcher<'a>
1426 core_str::StrExt::rsplit_terminator(self, pat)
1429 /// An iterator over substrings of `self`, separated by a pattern,
1430 /// restricted to returning
1431 /// at most `count` items.
1433 /// The last element returned, if any, will contain the remainder of the
1435 /// The pattern can be a simple `&str`, `char`, or a closure that
1436 /// determines the split.
1437 /// Additional libraries might provide more complex patterns like
1438 /// regular expressions.
1440 /// # Iterator behavior
1442 /// The returned iterator will not be double ended, because it is
1443 /// not efficient to support.
1445 /// If the pattern allows a reverse search, `rsplitn()` can be used.
1449 /// Simple patterns:
1452 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1453 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1455 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1456 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1458 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1459 /// assert_eq!(v, ["abcXdef"]);
1461 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1462 /// assert_eq!(v, [""]);
1465 /// A more complex pattern, using a closure:
1468 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1469 /// assert_eq!(v, ["abc", "defXghi"]);
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 pub fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
1473 core_str::StrExt::splitn(self, count, pat)
1476 /// An iterator over substrings of `self`, separated by a pattern,
1477 /// starting from the end of the string, restricted to returning
1478 /// at most `count` items.
1480 /// The last element returned, if any, will contain the remainder of the
1483 /// The pattern can be a simple `&str`, `char`, or a closure that
1484 /// determines the split.
1485 /// Additional libraries might provide more complex patterns like
1486 /// regular expressions.
1488 /// # Iterator behavior
1490 /// The returned iterator will not be double ended, because it is not
1491 /// efficient to support.
1493 /// `splitn()` can be used for splitting from the front.
1497 /// Simple patterns:
1500 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1501 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1503 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1504 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1506 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1507 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1510 /// A more complex pattern, using a closure:
1513 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1514 /// assert_eq!(v, ["ghi", "abc1def"]);
1516 #[stable(feature = "rust1", since = "1.0.0")]
1517 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
1518 where P::Searcher: ReverseSearcher<'a>
1520 core_str::StrExt::rsplitn(self, count, pat)
1523 /// An iterator over the matches of a pattern within `self`.
1525 /// The pattern can be a simple `&str`, `char`, or a closure that
1526 /// determines the split.
1527 /// Additional libraries might provide more complex patterns like
1528 /// regular expressions.
1530 /// # Iterator behavior
1532 /// The returned iterator will be double ended if the pattern allows
1533 /// a reverse search
1534 /// and forward/reverse search yields the same elements. This is true
1535 /// for, eg, `char` but not
1538 /// If the pattern allows a reverse search but its results might differ
1539 /// from a forward search, `rmatches()` can be used.
1544 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1545 /// assert_eq!(v, ["abc", "abc", "abc"]);
1547 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1548 /// assert_eq!(v, ["1", "2", "3"]);
1550 #[stable(feature = "str_matches", since = "1.2.0")]
1551 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1552 core_str::StrExt::matches(self, pat)
1555 /// An iterator over the matches of a pattern within `self`, yielded in
1558 /// The pattern can be a simple `&str`, `char`, or a closure that
1559 /// determines the split.
1560 /// Additional libraries might provide more complex patterns like
1561 /// regular expressions.
1563 /// # Iterator behavior
1565 /// The returned iterator requires that the pattern supports a
1567 /// and it will be double ended if a forward/reverse search yields
1568 /// the same elements.
1570 /// For iterating from the front, `matches()` can be used.
1575 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1576 /// assert_eq!(v, ["abc", "abc", "abc"]);
1578 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1579 /// assert_eq!(v, ["3", "2", "1"]);
1581 #[stable(feature = "str_matches", since = "1.2.0")]
1582 pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1583 where P::Searcher: ReverseSearcher<'a>
1585 core_str::StrExt::rmatches(self, pat)
1588 /// An iterator over the start and end indices of the disjoint matches
1589 /// of a pattern within `self`.
1591 /// For matches of `pat` within `self` that overlap, only the indices
1592 /// corresponding to the first
1593 /// match are returned.
1595 /// The pattern can be a simple `&str`, `char`, or a closure that
1598 /// Additional libraries might provide more complex patterns like
1599 /// regular expressions.
1601 /// # Iterator behavior
1603 /// The returned iterator will be double ended if the pattern allows a
1605 /// and forward/reverse search yields the same elements. This is true for,
1606 /// eg, `char` but not
1609 /// If the pattern allows a reverse search but its results might differ
1610 /// from a forward search, `rmatch_indices()` can be used.
1615 /// #![feature(str_match_indices)]
1617 /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
1618 /// assert_eq!(v, [(0, 3), (6, 9), (12, 15)]);
1620 /// let v: Vec<(usize, usize)> = "1abcabc2".match_indices("abc").collect();
1621 /// assert_eq!(v, [(1, 4), (4, 7)]);
1623 /// let v: Vec<(usize, usize)> = "ababa".match_indices("aba").collect();
1624 /// assert_eq!(v, [(0, 3)]); // only the first `aba`
1626 #[unstable(feature = "str_match_indices",
1627 reason = "might have its iterator type changed")]
1628 // NB: Right now MatchIndices yields `(usize, usize)`, but it would
1629 // be more consistent with `matches` and `char_indices` to return `(usize, &str)`
1630 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1631 core_str::StrExt::match_indices(self, pat)
1634 /// An iterator over the start and end indices of the disjoint matches of
1635 /// a pattern within
1636 /// `self`, yielded in reverse order.
1638 /// For matches of `pat` within `self` that overlap, only the indices
1639 /// corresponding to the last
1640 /// match are returned.
1642 /// The pattern can be a simple `&str`, `char`, or a closure that
1645 /// Additional libraries might provide more complex patterns like
1646 /// regular expressions.
1648 /// # Iterator behavior
1650 /// The returned iterator requires that the pattern supports a
1652 /// and it will be double ended if a forward/reverse search yields
1653 /// the same elements.
1655 /// For iterating from the front, `match_indices()` can be used.
1660 /// #![feature(str_match_indices)]
1662 /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1663 /// assert_eq!(v, [(12, 15), (6, 9), (0, 3)]);
1665 /// let v: Vec<(usize, usize)> = "1abcabc2".rmatch_indices("abc").collect();
1666 /// assert_eq!(v, [(4, 7), (1, 4)]);
1668 /// let v: Vec<(usize, usize)> = "ababa".rmatch_indices("aba").collect();
1669 /// assert_eq!(v, [(2, 5)]); // only the last `aba`
1671 #[unstable(feature = "str_match_indices",
1672 reason = "might have its iterator type changed")]
1673 // NB: Right now RMatchIndices yields `(usize, usize)`, but it would
1674 // be more consistent with `rmatches` and `char_indices` to return `(usize, &str)`
1675 pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1676 where P::Searcher: ReverseSearcher<'a>
1678 core_str::StrExt::rmatch_indices(self, pat)
1681 /// Returns the byte offset of an inner slice relative to an enclosing
1686 /// Panics if `inner` is not a direct slice contained within self.
1691 /// #![feature(subslice_offset)]
1693 /// let string = "a\nb\nc";
1694 /// let lines: Vec<&str> = string.lines().collect();
1696 /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
1697 /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
1698 /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
1700 #[unstable(feature = "subslice_offset",
1701 reason = "awaiting convention about comparability of arbitrary slices")]
1702 #[deprecated(since = "1.3.0",
1703 reason = "replaced with other pattern-related methods")]
1704 pub fn subslice_offset(&self, inner: &str) -> usize {
1705 core_str::StrExt::subslice_offset(self, inner)
1708 /// Returns a `&str` with leading and trailing whitespace removed.
1713 /// let s = " Hello\tworld\t";
1714 /// assert_eq!(s.trim(), "Hello\tworld");
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 pub fn trim(&self) -> &str {
1718 UnicodeStr::trim(self)
1721 /// Returns a `&str` with leading whitespace removed.
1726 /// let s = " Hello\tworld\t";
1727 /// assert_eq!(s.trim_left(), "Hello\tworld\t");
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 pub fn trim_left(&self) -> &str {
1731 UnicodeStr::trim_left(self)
1734 /// Returns a `&str` with trailing whitespace removed.
1739 /// let s = " Hello\tworld\t";
1740 /// assert_eq!(s.trim_right(), " Hello\tworld");
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 pub fn trim_right(&self) -> &str {
1744 UnicodeStr::trim_right(self)
1747 /// Returns a string with all pre- and suffixes that match a pattern
1748 /// repeatedly removed.
1750 /// The pattern can be a simple `char`, or a closure that determines
1755 /// Simple patterns:
1758 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1759 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1761 /// let x: &[_] = &['1', '2'];
1762 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1765 /// A more complex pattern, using a closure:
1768 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1770 #[stable(feature = "rust1", since = "1.0.0")]
1771 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1772 where P::Searcher: DoubleEndedSearcher<'a>
1774 core_str::StrExt::trim_matches(self, pat)
1777 /// Returns a string with all prefixes that match a pattern
1778 /// repeatedly removed.
1780 /// The pattern can be a simple `&str`, `char`, or a closure that
1781 /// determines the split.
1786 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1787 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1789 /// let x: &[_] = &['1', '2'];
1790 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1792 #[stable(feature = "rust1", since = "1.0.0")]
1793 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1794 core_str::StrExt::trim_left_matches(self, pat)
1797 /// Returns a string with all suffixes that match a pattern
1798 /// repeatedly removed.
1800 /// The pattern can be a simple `&str`, `char`, or a closure that
1801 /// determines the split.
1805 /// Simple patterns:
1808 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1809 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1811 /// let x: &[_] = &['1', '2'];
1812 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1815 /// A more complex pattern, using a closure:
1818 /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1822 where P::Searcher: ReverseSearcher<'a>
1824 core_str::StrExt::trim_right_matches(self, pat)
1827 /// Parses `self` into the specified type.
1831 /// Will return `Err` if it's not possible to parse `self` into the type.
1836 /// assert_eq!("4".parse::<u32>(), Ok(4));
1842 /// assert!("j".parse::<u32>().is_err());
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1847 core_str::StrExt::parse(self)
1850 /// Replaces all occurrences of one string with another.
1852 /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a
1853 /// second `&str` to
1854 /// replace it with. If the original `&str` isn't found, no change occurs.
1859 /// let s = "this is old";
1861 /// assert_eq!(s.replace("old", "new"), "this is new");
1864 /// When a `&str` isn't found:
1867 /// let s = "this is old";
1868 /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
1870 #[stable(feature = "rust1", since = "1.0.0")]
1871 pub fn replace(&self, from: &str, to: &str) -> String {
1872 let mut result = String::new();
1873 let mut last_end = 0;
1874 for (start, end) in self.match_indices(from) {
1875 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1876 result.push_str(to);
1879 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1883 /// Returns the lowercase equivalent of this string.
1888 /// let s = "HELLO";
1889 /// assert_eq!(s.to_lowercase(), "hello");
1891 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1892 pub fn to_lowercase(&self) -> String {
1893 let mut s = String::with_capacity(self.len());
1894 for (i, c) in self[..].char_indices() {
1896 // Σ maps to σ, except at the end of a word where it maps to ς.
1897 // This is the only conditional (contextual) but language-independent mapping
1898 // in `SpecialCasing.txt`,
1899 // so hard-code it rather than have a generic "condition" mechanim.
1900 // See https://github.com/rust-lang/rust/issues/26035
1901 map_uppercase_sigma(self, i, &mut s)
1903 s.extend(c.to_lowercase());
1908 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1909 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1910 // for the definition of `Final_Sigma`.
1911 debug_assert!('Σ'.len_utf8() == 2);
1913 case_ignoreable_then_cased(from[..i].chars().rev()) &&
1914 !case_ignoreable_then_cased(from[i + 2..].chars());
1915 to.push_str(if is_word_final { "ς" } else { "σ" });
1918 fn case_ignoreable_then_cased<I: Iterator<Item=char>>(iter: I) -> bool {
1919 use rustc_unicode::derived_property::{Cased, Case_Ignorable};
1920 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1921 Some(c) => Cased(c),
1927 /// Returns the uppercase equivalent of this string.
1932 /// let s = "hello";
1933 /// assert_eq!(s.to_uppercase(), "HELLO");
1935 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1936 pub fn to_uppercase(&self) -> String {
1937 let mut s = String::with_capacity(self.len());
1938 s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1942 /// Escapes each char in `s` with `char::escape_default`.
1943 #[unstable(feature = "str_escape",
1944 reason = "return type may change to be an iterator")]
1945 pub fn escape_default(&self) -> String {
1946 self.chars().flat_map(|c| c.escape_default()).collect()
1949 /// Escapes each char in `s` with `char::escape_unicode`.
1950 #[unstable(feature = "str_escape",
1951 reason = "return type may change to be an iterator")]
1952 pub fn escape_unicode(&self) -> String {
1953 self.chars().flat_map(|c| c.escape_unicode()).collect()
1956 /// Converts the `Box<str>` into a `String` without copying or allocating.
1957 #[unstable(feature = "box_str",
1958 reason = "recently added, matches RFC")]
1959 pub fn into_string(self: Box<str>) -> String {
1961 let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1962 String::from_utf8_unchecked(slice.into_vec())