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 // ignore-lexer-test FIXME #15679
13 //! Unicode string manipulation (the `str` type).
15 //! Rust's `str` type is one of the core primitive types of the language. `&str` is the borrowed
16 //! string type. This type of string can only be created from other strings, unless it is a
17 //! `&'static str` (see below). It is not possible to move out of borrowed strings because they are
22 //! Here's some code that uses a `&str`:
25 //! let s = "Hello, world.";
28 //! This `&str` is a `&'static str`, which is the type of string literals. They're `'static`
29 //! because literals are available for the entire lifetime of the program.
31 //! You can get a non-`'static` `&str` by taking a slice of a `String`:
34 //! # let some_string = "Hello, world.".to_string();
35 //! let s = &some_string;
40 //! Rust's string type, `str`, is a sequence of Unicode scalar values encoded as a stream of UTF-8
41 //! bytes. All [strings](../../reference.html#literals) are guaranteed to be validly encoded UTF-8
42 //! sequences. Additionally, strings are not null-terminated and can thus contain null bytes.
44 //! The actual representation of `str`s have direct mappings to slices: `&str` is the same as
47 #![doc(primitive = "str")]
48 #![stable(feature = "rust1", since = "1.0.0")]
50 use self::RecompositionState::*;
51 use self::DecompositionType::*;
53 use core::clone::Clone;
54 use core::iter::AdditiveIterator;
55 use core::iter::{Iterator, Extend};
56 use core::option::Option::{self, Some, None};
57 use core::result::Result;
58 use core::str as core_str;
59 use unicode::str::{UnicodeStr, Utf16Encoder};
61 use core::convert::AsRef;
62 use vec_deque::VecDeque;
63 use borrow::{Borrow, ToOwned};
67 use slice::SliceConcatExt;
69 pub use core::str::{FromStr, Utf8Error, Str};
70 pub use core::str::{Lines, LinesAny, MatchIndices, CharRange};
71 pub use core::str::{Split, SplitTerminator, SplitN};
72 pub use core::str::{RSplit, RSplitN};
73 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
74 pub use core::str::{from_utf8_unchecked, ParseBoolError};
75 pub use unicode::str::{Words, Graphemes, GraphemeIndices};
76 pub use core::str::Pattern;
77 pub use core::str::{Searcher, ReverseSearcher, DoubleEndedSearcher, SearchStep};
80 Section: Creating a string
83 impl<S: AsRef<str>> SliceConcatExt<str, String> for [S] {
84 fn concat(&self) -> String {
89 // `len` calculation may overflow but push_str will check boundaries
90 let len = self.iter().map(|s| s.as_ref().len()).sum();
91 let mut result = String::with_capacity(len);
94 result.push_str(s.as_ref())
100 fn connect(&self, sep: &str) -> String {
102 return String::new();
107 return self.concat();
110 // this is wrong without the guarantee that `self` is non-empty
111 // `len` calculation may overflow but push_str but will check boundaries
112 let len = sep.len() * (self.len() - 1)
113 + self.iter().map(|s| s.as_ref().len()).sum();
114 let mut result = String::with_capacity(len);
115 let mut first = true;
121 result.push_str(sep);
123 result.push_str(s.as_ref());
133 // Helper functions used for Unicode normalization
134 fn canonical_sort(comb: &mut [(char, u8)]) {
135 let len = comb.len();
137 let mut swapped = false;
139 let class_a = comb[j-1].1;
140 let class_b = comb[j].1;
141 if class_a != 0 && class_b != 0 && class_a > class_b {
146 if !swapped { break; }
151 enum DecompositionType {
156 /// External iterator for a string decomposition's characters.
158 /// For use with the `std::iter` module.
160 #[unstable(feature = "unicode",
161 reason = "this functionality may be replaced with a more generic \
162 unicode crate on crates.io")]
163 pub struct Decompositions<'a> {
164 kind: DecompositionType,
166 buffer: Vec<(char, u8)>,
170 #[stable(feature = "rust1", since = "1.0.0")]
171 impl<'a> Iterator for Decompositions<'a> {
175 fn next(&mut self) -> Option<char> {
176 match self.buffer.first() {
179 self.buffer.remove(0);
182 Some(&(c, _)) if self.sorted => {
183 self.buffer.remove(0);
186 _ => self.sorted = false
190 for ch in self.iter.by_ref() {
191 let buffer = &mut self.buffer;
192 let sorted = &mut self.sorted;
196 unicode::char::canonical_combining_class(d);
197 if class == 0 && !*sorted {
198 canonical_sort(buffer);
201 buffer.push((d, class));
205 unicode::char::decompose_canonical(ch, callback)
208 unicode::char::decompose_compatible(ch, callback)
219 canonical_sort(&mut self.buffer);
223 if self.buffer.is_empty() {
226 match self.buffer.remove(0) {
236 fn size_hint(&self) -> (usize, Option<usize>) {
237 let (lower, _) = self.iter.size_hint();
243 enum RecompositionState {
249 /// External iterator for a string recomposition's characters.
251 /// For use with the `std::iter` module.
253 #[unstable(feature = "unicode",
254 reason = "this functionality may be replaced with a more generic \
255 unicode crate on crates.io")]
256 pub struct Recompositions<'a> {
257 iter: Decompositions<'a>,
258 state: RecompositionState,
259 buffer: VecDeque<char>,
260 composee: Option<char>,
264 #[stable(feature = "rust1", since = "1.0.0")]
265 impl<'a> Iterator for Recompositions<'a> {
269 fn next(&mut self) -> Option<char> {
273 for ch in self.iter.by_ref() {
274 let ch_class = unicode::char::canonical_combining_class(ch);
275 if self.composee.is_none() {
279 self.composee = Some(ch);
282 let k = self.composee.clone().unwrap();
284 match self.last_ccc {
286 match unicode::char::compose(k, ch) {
288 self.composee = Some(r);
293 self.composee = Some(ch);
296 self.buffer.push_back(ch);
297 self.last_ccc = Some(ch_class);
302 if l_class >= ch_class {
303 // `ch` is blocked from `composee`
305 self.composee = Some(ch);
306 self.last_ccc = None;
307 self.state = Purging;
310 self.buffer.push_back(ch);
311 self.last_ccc = Some(ch_class);
314 match unicode::char::compose(k, ch) {
316 self.composee = Some(r);
320 self.buffer.push_back(ch);
321 self.last_ccc = Some(ch_class);
327 self.state = Finished;
328 if self.composee.is_some() {
329 return self.composee.take();
333 match self.buffer.pop_front() {
334 None => self.state = Composing,
339 match self.buffer.pop_front() {
340 None => return self.composee.take(),
349 /// External iterator for a string's UTF16 codeunits.
351 /// For use with the `std::iter` module.
353 #[unstable(feature = "collections")]
354 pub struct Utf16Units<'a> {
355 encoder: Utf16Encoder<Chars<'a>>
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl<'a> Iterator for Utf16Units<'a> {
363 fn next(&mut self) -> Option<u16> { self.encoder.next() }
366 fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
373 // Return the initial codepoint accumulator for the first byte.
374 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
375 // for width 3, and 3 bits for width 4
376 macro_rules! utf8_first_byte {
377 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
380 // return the value of $ch updated with continuation byte $byte
381 macro_rules! utf8_acc_cont_byte {
382 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
385 #[stable(feature = "rust1", since = "1.0.0")]
386 impl Borrow<str> for String {
387 fn borrow(&self) -> &str { &self[..] }
390 #[stable(feature = "rust1", since = "1.0.0")]
391 impl ToOwned for str {
393 fn to_owned(&self) -> String {
395 String::from_utf8_unchecked(self.as_bytes().to_owned())
405 Section: Trait implementations
409 /// Any string that can be represented as a slice.
412 #[stable(feature = "rust1", since = "1.0.0")]
414 /// Escapes each char in `s` with `char::escape_default`.
415 #[unstable(feature = "collections",
416 reason = "return type may change to be an iterator")]
417 pub fn escape_default(&self) -> String {
418 self.chars().flat_map(|c| c.escape_default()).collect()
421 /// Escapes each char in `s` with `char::escape_unicode`.
422 #[unstable(feature = "collections",
423 reason = "return type may change to be an iterator")]
424 pub fn escape_unicode(&self) -> String {
425 self.chars().flat_map(|c| c.escape_unicode()).collect()
428 /// Replaces all occurrences of one string with another.
430 /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a second `&str` to
431 /// replace it with. If the original `&str` isn't found, no change occurs.
436 /// let s = "this is old";
438 /// assert_eq!(s.replace("old", "new"), "this is new");
441 /// When a `&str` isn't found:
444 /// let s = "this is old";
445 /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
447 #[stable(feature = "rust1", since = "1.0.0")]
448 pub fn replace(&self, from: &str, to: &str) -> String {
449 let mut result = String::new();
450 let mut last_end = 0;
451 for (start, end) in self.match_indices(from) {
452 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
456 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
460 /// Returns an iterator over the string in Unicode Normalization Form D
461 /// (canonical decomposition).
463 #[unstable(feature = "unicode",
464 reason = "this functionality may be replaced with a more generic \
465 unicode crate on crates.io")]
466 pub fn nfd_chars(&self) -> Decompositions {
468 iter: self[..].chars(),
475 /// Returns an iterator over the string in Unicode Normalization Form KD
476 /// (compatibility decomposition).
478 #[unstable(feature = "unicode",
479 reason = "this functionality may be replaced with a more generic \
480 unicode crate on crates.io")]
481 pub fn nfkd_chars(&self) -> Decompositions {
483 iter: self[..].chars(),
490 /// An Iterator over the string in Unicode Normalization Form C
491 /// (canonical decomposition followed by canonical composition).
493 #[unstable(feature = "unicode",
494 reason = "this functionality may be replaced with a more generic \
495 unicode crate on crates.io")]
496 pub fn nfc_chars(&self) -> Recompositions {
498 iter: self.nfd_chars(),
500 buffer: VecDeque::new(),
506 /// An Iterator over the string in Unicode Normalization Form KC
507 /// (compatibility decomposition followed by canonical composition).
509 #[unstable(feature = "unicode",
510 reason = "this functionality may be replaced with a more generic \
511 unicode crate on crates.io")]
512 pub fn nfkc_chars(&self) -> Recompositions {
514 iter: self.nfkd_chars(),
516 buffer: VecDeque::new(),
522 /// Returns `true` if `self` contains another `&str`.
527 /// assert!("bananas".contains("nana"));
529 /// assert!(!"bananas".contains("foobar"));
531 #[stable(feature = "rust1", since = "1.0.0")]
532 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
533 core_str::StrExt::contains(&self[..], pat)
536 /// An iterator over the codepoints of `self`.
541 /// let v: Vec<char> = "abc åäö".chars().collect();
543 /// assert_eq!(v, ['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
545 #[stable(feature = "rust1", since = "1.0.0")]
546 pub fn chars(&self) -> Chars {
547 core_str::StrExt::chars(&self[..])
550 /// An iterator over the bytes of `self`.
555 /// let v: Vec<u8> = "bors".bytes().collect();
557 /// assert_eq!(v, b"bors".to_vec());
559 #[stable(feature = "rust1", since = "1.0.0")]
560 pub fn bytes(&self) -> Bytes {
561 core_str::StrExt::bytes(&self[..])
564 /// An iterator over the characters of `self` and their byte offsets.
569 /// let v: Vec<(usize, char)> = "abc".char_indices().collect();
570 /// let b = vec![(0, 'a'), (1, 'b'), (2, 'c')];
572 /// assert_eq!(v, b);
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn char_indices(&self) -> CharIndices {
576 core_str::StrExt::char_indices(&self[..])
579 /// An iterator over substrings of `self`, separated by characters
580 /// matched by a pattern.
582 /// The pattern can be a simple `&str`, or a closure that determines
587 /// Simple `&str` patterns:
590 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
591 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
593 /// let v: Vec<&str> = "".split('X').collect();
594 /// assert_eq!(v, [""]);
597 /// More complex patterns with a lambda:
600 /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
601 /// assert_eq!(v, ["abc", "def", "ghi"]);
603 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
604 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
606 #[stable(feature = "rust1", since = "1.0.0")]
607 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
608 core_str::StrExt::split(&self[..], pat)
611 /// An iterator over substrings of `self`, separated by characters matched by a pattern,
612 /// restricted to splitting at most `count` times.
614 /// The pattern can be a simple `&str`, or a closure that determines
619 /// Simple `&str` patterns:
622 /// let v: Vec<&str> = "Mary had a little lambda".splitn(2, ' ').collect();
623 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
625 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(2, 'X').collect();
626 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
628 /// let v: Vec<&str> = "abcXdef".splitn(0, 'X').collect();
629 /// assert_eq!(v, ["abcXdef"]);
631 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
632 /// assert_eq!(v, [""]);
635 /// More complex patterns with a lambda:
638 /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |c: char| c.is_numeric()).collect();
639 /// assert_eq!(v, ["abc", "def2ghi"]);
641 #[stable(feature = "rust1", since = "1.0.0")]
642 pub fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
643 core_str::StrExt::splitn(&self[..], count, pat)
646 /// An iterator over substrings of `self`, separated by characters
647 /// matched by a pattern.
649 /// Equivalent to `split`, except that the trailing substring is skipped if empty.
651 /// The pattern can be a simple `&str`, or a closure that determines
656 /// Simple `&str` patterns:
659 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
660 /// assert_eq!(v, ["A", "B"]);
662 /// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
663 /// assert_eq!(v, ["A", "", "B", ""]);
666 /// More complex patterns with a lambda:
669 /// let v: Vec<&str> = "abc1def2ghi3".split_terminator(|c: char| c.is_numeric()).collect();
670 /// assert_eq!(v, ["abc", "def", "ghi"]);
672 #[stable(feature = "rust1", since = "1.0.0")]
673 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
674 core_str::StrExt::split_terminator(&self[..], pat)
677 /// An iterator over substrings of `self`, separated by a pattern,
678 /// starting from the end of the string.
685 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
686 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
688 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
689 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
692 /// More complex patterns with a lambda:
695 /// let v: Vec<&str> = "abc1def2ghi".rsplit(|c: char| c.is_numeric()).collect();
696 /// assert_eq!(v, ["ghi", "def", "abc"]);
698 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
700 where P::Searcher: ReverseSearcher<'a>
702 core_str::StrExt::rsplit(&self[..], pat)
705 /// An iterator over substrings of `self`, separated by a pattern,
706 /// starting from the end of the string, restricted to splitting
707 /// at most `count` times.
714 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
715 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
717 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(1, "::").collect();
718 /// assert_eq!(v, ["leopard", "lion::tiger"]);
721 /// More complex patterns with a lambda:
724 /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |c: char| c.is_numeric()).collect();
725 /// assert_eq!(v, ["ghi", "abc1def"]);
727 #[stable(feature = "rust1", since = "1.0.0")]
728 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
729 where P::Searcher: ReverseSearcher<'a>
731 core_str::StrExt::rsplitn(&self[..], count, pat)
734 /// An iterator over the start and end indices of the disjoint matches of a `&str` within
737 /// That is, each returned value `(start, end)` satisfies `self.slice(start, end) == sep`. For
738 /// matches of `sep` within `self` that overlap, only the indices corresponding to the first
739 /// match are returned.
744 /// # #![feature(collections)]
745 /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
746 /// assert_eq!(v, [(0,3), (6,9), (12,15)]);
748 /// let v: Vec<(usize, usize)> = "1abcabc2".match_indices("abc").collect();
749 /// assert_eq!(v, [(1,4), (4,7)]);
751 /// let v: Vec<(usize, usize)> = "ababa".match_indices("aba").collect();
752 /// assert_eq!(v, [(0, 3)]); // only the first `aba`
754 #[unstable(feature = "collections",
755 reason = "might have its iterator type changed")]
756 // NB: Right now MatchIndices yields `(usize, usize)`,
757 // but it would be more consistent and useful to return `(usize, &str)`
758 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
759 core_str::StrExt::match_indices(&self[..], pat)
762 /// An iterator over the lines of a string, separated by `\n`.
764 /// This does not include the empty string after a trailing `\n`.
769 /// let four_lines = "foo\nbar\n\nbaz";
770 /// let v: Vec<&str> = four_lines.lines().collect();
772 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
775 /// Leaving off the trailing character:
778 /// let four_lines = "foo\nbar\n\nbaz\n";
779 /// let v: Vec<&str> = four_lines.lines().collect();
781 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub fn lines(&self) -> Lines {
785 core_str::StrExt::lines(&self[..])
788 /// An iterator over the lines of a string, separated by either `\n` or `\r\n`.
790 /// As with `.lines()`, this does not include an empty trailing line.
795 /// let four_lines = "foo\r\nbar\n\r\nbaz";
796 /// let v: Vec<&str> = four_lines.lines_any().collect();
798 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
801 /// Leaving off the trailing character:
804 /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
805 /// let v: Vec<&str> = four_lines.lines_any().collect();
807 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
809 #[stable(feature = "rust1", since = "1.0.0")]
810 pub fn lines_any(&self) -> LinesAny {
811 core_str::StrExt::lines_any(&self[..])
813 /// Returns a slice of the string from the character range [`begin`..`end`).
815 /// That is, start at the `begin`-th code point of the string and continue
816 /// to the `end`-th code point. This does not detect or handle edge cases
817 /// such as leaving a combining character as the first code point of the
820 /// Due to the design of UTF-8, this operation is `O(end)`. See `slice`,
821 /// `slice_to` and `slice_from` for `O(1)` variants that use byte indices
822 /// rather than code point indices.
826 /// Panics if `begin` > `end` or the either `begin` or `end` are beyond the
827 /// last character of the string.
832 /// # #![feature(collections)]
833 /// let s = "Löwe 老虎 Léopard";
835 /// assert_eq!(s.slice_chars(0, 4), "Löwe");
836 /// assert_eq!(s.slice_chars(5, 7), "老虎");
838 #[unstable(feature = "collections",
839 reason = "may have yet to prove its worth")]
840 pub fn slice_chars(&self, begin: usize, end: usize) -> &str {
841 core_str::StrExt::slice_chars(&self[..], begin, end)
844 /// Takes a bytewise slice from a string.
846 /// Returns the substring from [`begin`..`end`).
850 /// Caller must check both UTF-8 character boundaries and the boundaries of the entire slice as
856 /// let s = "Löwe 老虎 Léopard";
859 /// assert_eq!(s.slice_unchecked(0, 21), "Löwe 老虎 Léopard");
862 #[stable(feature = "rust1", since = "1.0.0")]
863 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
864 core_str::StrExt::slice_unchecked(&self[..], begin, end)
867 /// Returns `true` if the given `&str` is a prefix of the string.
872 /// assert!("banana".starts_with("ba"));
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
876 core_str::StrExt::starts_with(&self[..], pat)
879 /// Returns true if the given `&str` is a suffix of the string.
884 /// assert!("banana".ends_with("nana"));
886 #[stable(feature = "rust1", since = "1.0.0")]
887 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
888 where P::Searcher: ReverseSearcher<'a>
890 core_str::StrExt::ends_with(&self[..], pat)
893 /// Returns a string with all pre- and suffixes that match a pattern repeatedly removed.
895 /// The pattern can be a simple `&str`, or a closure that determines the split.
899 /// Simple `&str` patterns:
902 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
904 /// let x: &[_] = &['1', '2'];
905 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
908 /// More complex patterns with a lambda:
911 /// assert_eq!("123foo1bar123".trim_matches(|c: char| c.is_numeric()), "foo1bar");
913 #[stable(feature = "rust1", since = "1.0.0")]
914 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
915 where P::Searcher: DoubleEndedSearcher<'a>
917 core_str::StrExt::trim_matches(&self[..], pat)
920 /// Returns a string with all prefixes that match a pattern repeatedly removed.
922 /// The pattern can be a simple `&str`, or a closure that determines the split.
926 /// Simple `&str` patterns:
929 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
931 /// let x: &[_] = &['1', '2'];
932 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
935 /// More complex patterns with a lambda:
938 /// assert_eq!("123foo1bar123".trim_left_matches(|c: char| c.is_numeric()), "foo1bar123");
940 #[stable(feature = "rust1", since = "1.0.0")]
941 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
942 core_str::StrExt::trim_left_matches(&self[..], pat)
945 /// Returns a string with all suffixes that match a pattern repeatedly removed.
947 /// The pattern can be a simple `&str`, or a closure that determines the split.
951 /// Simple `&str` patterns:
954 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
955 /// let x: &[_] = &['1', '2'];
956 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
959 /// More complex patterns with a lambda:
962 /// assert_eq!("123foo1bar123".trim_right_matches(|c: char| c.is_numeric()), "123foo1bar");
964 #[stable(feature = "rust1", since = "1.0.0")]
965 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
966 where P::Searcher: ReverseSearcher<'a>
968 core_str::StrExt::trim_right_matches(&self[..], pat)
971 /// Check that `index`-th byte lies at the start and/or end of a UTF-8 code point sequence.
973 /// The start and end of the string (when `index == self.len()`) are considered to be
978 /// Panics if `index` is greater than `self.len()`.
983 /// # #![feature(str_char)]
984 /// let s = "Löwe 老虎 Léopard";
985 /// assert!(s.is_char_boundary(0));
987 /// assert!(s.is_char_boundary(6));
988 /// assert!(s.is_char_boundary(s.len()));
990 /// // second byte of `ö`
991 /// assert!(!s.is_char_boundary(2));
993 /// // third byte of `老`
994 /// assert!(!s.is_char_boundary(8));
996 #[unstable(feature = "str_char",
997 reason = "it is unclear whether this method pulls its weight \
998 with the existence of the char_indices iterator or \
999 this method may want to be replaced with checked \
1001 pub fn is_char_boundary(&self, index: usize) -> bool {
1002 core_str::StrExt::is_char_boundary(&self[..], index)
1005 /// Given a byte position, return the next char and its index.
1007 /// This can be used to iterate over the Unicode characters of a string.
1011 /// If `i` is greater than or equal to the length of the string.
1012 /// If `i` is not the index of the beginning of a valid UTF-8 character.
1016 /// This example manually iterates through the characters of a string; this should normally be
1017 /// done by `.chars()` or `.char_indices()`.
1020 /// # #![feature(str_char, core)]
1021 /// use std::str::CharRange;
1023 /// let s = "中华Việt Nam";
1025 /// while i < s.len() {
1026 /// let CharRange {ch, next} = s.char_range_at(i);
1027 /// println!("{}: {}", i, ch);
1046 #[unstable(feature = "str_char",
1047 reason = "often replaced by char_indices, this method may \
1048 be removed in favor of just char_at() or eventually \
1049 removed altogether")]
1050 pub fn char_range_at(&self, start: usize) -> CharRange {
1051 core_str::StrExt::char_range_at(&self[..], start)
1054 /// Given a byte position, return the previous `char` and its position.
1056 /// This function can be used to iterate over a Unicode string in reverse.
1058 /// Returns 0 for next index if called on start index 0.
1062 /// If `i` is greater than the length of the string.
1063 /// If `i` is not an index following a valid UTF-8 character.
1067 /// This example manually iterates through the characters of a string; this should normally be
1068 /// done by `.chars().rev()` or `.char_indices()`.
1071 /// # #![feature(str_char, core)]
1072 /// use std::str::CharRange;
1074 /// let s = "中华Việt Nam";
1075 /// let mut i = s.len();
1077 /// let CharRange {ch, next} = s.char_range_at_reverse(i);
1078 /// println!("{}: {}", i, ch);
1097 #[unstable(feature = "str_char",
1098 reason = "often replaced by char_indices, this method may \
1099 be removed in favor of just char_at_reverse() or \
1100 eventually removed altogether")]
1101 pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
1102 core_str::StrExt::char_range_at_reverse(&self[..], start)
1105 /// Given a byte position, return the `char` at that position.
1109 /// If `i` is greater than or equal to the length of the string.
1110 /// If `i` is not the index of the beginning of a valid UTF-8 character.
1115 /// # #![feature(str_char)]
1117 /// assert_eq!(s.char_at(1), 'b');
1118 /// assert_eq!(s.char_at(2), 'π');
1120 #[unstable(feature = "str_char",
1121 reason = "frequently replaced by the chars() iterator, this \
1122 method may be removed or possibly renamed in the \
1123 future; it is normally replaced by chars/char_indices \
1124 iterators or by getting the first char from a \
1126 pub fn char_at(&self, i: usize) -> char {
1127 core_str::StrExt::char_at(&self[..], i)
1130 /// Given a byte position, return the `char` at that position, counting from the end.
1134 /// If `i` is greater than the length of the string.
1135 /// If `i` is not an index following a valid UTF-8 character.
1140 /// # #![feature(str_char)]
1142 /// assert_eq!(s.char_at_reverse(1), 'a');
1143 /// assert_eq!(s.char_at_reverse(2), 'b');
1145 #[unstable(feature = "str_char",
1146 reason = "see char_at for more details, but reverse semantics \
1147 are also somewhat unclear, especially with which \
1148 cases generate panics")]
1149 pub fn char_at_reverse(&self, i: usize) -> char {
1150 core_str::StrExt::char_at_reverse(&self[..], i)
1153 /// Convert `self` to a byte slice.
1158 /// assert_eq!("bors".as_bytes(), b"bors");
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 pub fn as_bytes(&self) -> &[u8] {
1162 core_str::StrExt::as_bytes(&self[..])
1165 /// Returns the byte index of the first character of `self` that matches the pattern, if it
1168 /// Returns `None` if it doesn't exist.
1170 /// The pattern can be a simple `&str`, or a closure that determines the split.
1174 /// Simple `&str` patterns:
1177 /// let s = "Löwe 老虎 Léopard";
1179 /// assert_eq!(s.find('L'), Some(0));
1180 /// assert_eq!(s.find('é'), Some(14));
1184 /// More complex patterns with a lambda:
1187 /// let s = "Löwe 老虎 Léopard";
1189 /// assert_eq!(s.find(|c: char| c.is_whitespace()), Some(5));
1192 /// Not finding the pattern:
1195 /// let s = "Löwe 老虎 Léopard";
1196 /// let x: &[_] = &['1', '2'];
1198 /// assert_eq!(s.find(x), None);
1200 #[stable(feature = "rust1", since = "1.0.0")]
1201 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1202 core_str::StrExt::find(&self[..], pat)
1205 /// Returns the byte index of the last character of `self` that matches the pattern, if it
1208 /// Returns `None` if it doesn't exist.
1210 /// The pattern can be a simple `&str`, or a closure that determines the split.
1214 /// Simple `&str` patterns:
1217 /// let s = "Löwe 老虎 Léopard";
1219 /// assert_eq!(s.rfind('L'), Some(13));
1220 /// assert_eq!(s.rfind('é'), Some(14));
1223 /// More complex patterns with a lambda:
1226 /// let s = "Löwe 老虎 Léopard";
1228 /// assert_eq!(s.rfind(|c: char| c.is_whitespace()), Some(12));
1231 /// Not finding the pattern:
1234 /// let s = "Löwe 老虎 Léopard";
1235 /// let x: &[_] = &['1', '2'];
1237 /// assert_eq!(s.rfind(x), None);
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1241 where P::Searcher: ReverseSearcher<'a>
1243 core_str::StrExt::rfind(&self[..], pat)
1246 /// Retrieves the first character from a `&str` and returns it.
1248 /// This does not allocate a new string; instead, it returns a slice that points one character
1249 /// beyond the character that was shifted.
1251 /// If the slice does not contain any characters, None is returned instead.
1256 /// # #![feature(str_char)]
1257 /// let s = "Löwe 老虎 Léopard";
1258 /// let (c, s1) = s.slice_shift_char().unwrap();
1260 /// assert_eq!(c, 'L');
1261 /// assert_eq!(s1, "öwe 老虎 Léopard");
1263 /// let (c, s2) = s1.slice_shift_char().unwrap();
1265 /// assert_eq!(c, 'ö');
1266 /// assert_eq!(s2, "we 老虎 Léopard");
1268 #[unstable(feature = "str_char",
1269 reason = "awaiting conventions about shifting and slices and \
1270 may not be warranted with the existence of the chars \
1271 and/or char_indices iterators")]
1272 pub fn slice_shift_char(&self) -> Option<(char, &str)> {
1273 core_str::StrExt::slice_shift_char(&self[..])
1276 /// Returns the byte offset of an inner slice relative to an enclosing outer slice.
1280 /// Panics if `inner` is not a direct slice contained within self.
1285 /// # #![feature(collections)]
1286 /// let string = "a\nb\nc";
1287 /// let lines: Vec<&str> = string.lines().collect();
1289 /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
1290 /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
1291 /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
1293 #[unstable(feature = "collections",
1294 reason = "awaiting convention about comparability of arbitrary slices")]
1295 pub fn subslice_offset(&self, inner: &str) -> usize {
1296 core_str::StrExt::subslice_offset(&self[..], inner)
1299 /// Return an unsafe pointer to the `&str`'s buffer.
1301 /// The caller must ensure that the string outlives this pointer, and that it is not
1302 /// reallocated (e.g. by pushing to the string).
1307 /// let s = "Hello";
1308 /// let p = s.as_ptr();
1310 #[stable(feature = "rust1", since = "1.0.0")]
1312 pub fn as_ptr(&self) -> *const u8 {
1313 core_str::StrExt::as_ptr(&self[..])
1316 /// Return an iterator of `u16` over the string encoded as UTF-16.
1317 #[unstable(feature = "collections",
1318 reason = "this functionality may only be provided by libunicode")]
1319 pub fn utf16_units(&self) -> Utf16Units {
1320 Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
1323 /// Returns the length of `self` in bytes.
1328 /// assert_eq!("foo".len(), 3);
1329 /// assert_eq!("ƒoo".len(), 4); // fancy f!
1331 #[stable(feature = "rust1", since = "1.0.0")]
1333 pub fn len(&self) -> usize {
1334 core_str::StrExt::len(&self[..])
1337 /// Returns true if this slice has a length of zero bytes.
1342 /// assert!("".is_empty());
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 pub fn is_empty(&self) -> bool {
1347 core_str::StrExt::is_empty(&self[..])
1350 /// Parses `self` into the specified type.
1354 /// Will return `Err` if it's not possible to parse `self` into the type.
1359 /// assert_eq!("4".parse::<u32>(), Ok(4));
1365 /// assert!("j".parse::<u32>().is_err());
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1370 core_str::StrExt::parse(&self[..])
1373 /// Returns an iterator over the [grapheme clusters][graphemes] of `self`.
1375 /// [graphemes]: http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
1377 /// If `is_extended` is true, the iterator is over the *extended grapheme clusters*;
1378 /// otherwise, the iterator is over the *legacy grapheme clusters*.
1379 /// [UAX#29](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
1380 /// recommends extended grapheme cluster boundaries for general processing.
1385 /// # #![feature(unicode, core)]
1386 /// let gr1 = "a\u{310}e\u{301}o\u{308}\u{332}".graphemes(true).collect::<Vec<&str>>();
1387 /// let b: &[_] = &["a\u{310}", "e\u{301}", "o\u{308}\u{332}"];
1389 /// assert_eq!(&gr1[..], b);
1391 /// let gr2 = "a\r\nb🇷🇺🇸🇹".graphemes(true).collect::<Vec<&str>>();
1392 /// let b: &[_] = &["a", "\r\n", "b", "🇷🇺🇸🇹"];
1394 /// assert_eq!(&gr2[..], b);
1396 #[unstable(feature = "unicode",
1397 reason = "this functionality may only be provided by libunicode")]
1398 pub fn graphemes(&self, is_extended: bool) -> Graphemes {
1399 UnicodeStr::graphemes(&self[..], is_extended)
1402 /// Returns an iterator over the grapheme clusters of `self` and their byte offsets. See
1403 /// `graphemes()` for more information.
1408 /// # #![feature(unicode, core)]
1409 /// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(usize, &str)>>();
1410 /// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
1412 /// assert_eq!(&gr_inds[..], b);
1414 #[unstable(feature = "unicode",
1415 reason = "this functionality may only be provided by libunicode")]
1416 pub fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices {
1417 UnicodeStr::grapheme_indices(&self[..], is_extended)
1420 /// An iterator over the non-empty words of `self`.
1422 /// A 'word' is a subsequence separated by any sequence of whitespace. Sequences of whitespace
1423 /// are collapsed, so empty "words" are not included.
1428 /// # #![feature(str_words)]
1429 /// let some_words = " Mary had\ta little \n\t lamb";
1430 /// let v: Vec<&str> = some_words.words().collect();
1432 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1434 #[unstable(feature = "str_words",
1435 reason = "the precise algorithm to use is unclear")]
1436 pub fn words(&self) -> Words {
1437 UnicodeStr::words(&self[..])
1440 /// Returns a string's displayed width in columns.
1442 /// Control characters have zero width.
1444 /// `is_cjk` determines behavior for characters in the Ambiguous category: if `is_cjk` is
1445 /// `true`, these are 2 columns wide; otherwise, they are 1. In CJK locales, `is_cjk` should be
1446 /// `true`, else it should be `false`.
1447 /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) recommends that these
1448 /// characters be treated as 1 column (i.e., `is_cjk = false`) if the locale is unknown.
1449 #[unstable(feature = "unicode",
1450 reason = "this functionality may only be provided by libunicode")]
1451 pub fn width(&self, is_cjk: bool) -> usize {
1452 UnicodeStr::width(&self[..], is_cjk)
1455 /// Returns a `&str` with leading and trailing whitespace removed.
1460 /// let s = " Hello\tworld\t";
1461 /// assert_eq!(s.trim(), "Hello\tworld");
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 pub fn trim(&self) -> &str {
1465 UnicodeStr::trim(&self[..])
1468 /// Returns a `&str` with leading whitespace removed.
1473 /// let s = " Hello\tworld\t";
1474 /// assert_eq!(s.trim_left(), "Hello\tworld\t");
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 pub fn trim_left(&self) -> &str {
1478 UnicodeStr::trim_left(&self[..])
1481 /// Returns a `&str` with trailing whitespace removed.
1486 /// let s = " Hello\tworld\t";
1487 /// assert_eq!(s.trim_right(), " Hello\tworld");
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 pub fn trim_right(&self) -> &str {
1491 UnicodeStr::trim_right(&self[..])
1494 /// Returns the lowercase equivalent of this string.
1498 /// let s = "HELLO";
1499 /// assert_eq!(s.to_lowercase(), "hello");
1500 #[unstable(feature = "collections")]
1501 pub fn to_lowercase(&self) -> String {
1502 let mut s = String::with_capacity(self.len());
1503 s.extend(self[..].chars().flat_map(|c| c.to_lowercase()));
1507 /// Returns the uppercase equivalent of this string.
1511 /// let s = "hello";
1512 /// assert_eq!(s.to_uppercase(), "HELLO");
1513 #[unstable(feature = "collections")]
1514 pub fn to_uppercase(&self) -> String {
1515 let mut s = String::with_capacity(self.len());
1516 s.extend(self[..].chars().flat_map(|c| c.to_uppercase()));