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`](../primitive.str.html) type).
15 //! Rust's [`str`](../primitive.str.html) type is one of the core primitive
16 //! types of the language. `&str` is the borrowed string type. This type of
17 //! string can only be created from other strings, unless it is a `&'static str`
18 //! (see below). It is not possible to move out of borrowed strings because they
19 //! are owned elsewhere.
21 //! Basic operations are implemented directly by the compiler, but more advanced
22 //! operations are defined on the [`StrExt`](trait.StrExt.html) trait.
26 //! Here's some code that uses a `&str`:
29 //! let s = "Hello, world.";
32 //! This `&str` is a `&'static str`, which is the type of string literals.
33 //! They're `'static` because literals are available for the entire lifetime of
36 //! You can get a non-`'static` `&str` by taking a slice of a `String`:
39 //! # let some_string = "Hello, world.".to_string();
40 //! let s = &some_string;
45 //! Rust's string type, `str`, is a sequence of Unicode scalar values encoded as
46 //! a stream of UTF-8 bytes. All [strings](../../reference.html#literals) are
47 //! guaranteed to be validly encoded UTF-8 sequences. Additionally, strings are
48 //! not null-terminated and can thus contain null bytes.
50 //! The actual representation of `str`s have direct mappings to slices: `&str`
51 //! is the same as `&[u8]`.
53 #![doc(primitive = "str")]
54 #![stable(feature = "rust1", since = "1.0.0")]
56 use self::RecompositionState::*;
57 use self::DecompositionType::*;
59 use core::clone::Clone;
60 use core::iter::AdditiveIterator;
61 use core::iter::{Iterator, IteratorExt, Extend};
62 use core::option::Option::{self, Some, None};
63 use core::result::Result;
64 use core::slice::AsSlice;
65 use core::str as core_str;
66 use unicode::str::{UnicodeStr, Utf16Encoder};
68 use vec_deque::VecDeque;
69 use borrow::{Borrow, ToOwned};
73 use slice::SliceConcatExt;
75 pub use core::str::{FromStr, Utf8Error, Str};
76 pub use core::str::{Lines, LinesAny, MatchIndices, SplitStr, CharRange};
77 pub use core::str::{Split, SplitTerminator, SplitN};
78 pub use core::str::{RSplit, RSplitN};
79 pub use core::str::{from_utf8, CharEq, Chars, CharIndices, Bytes};
80 pub use core::str::{from_utf8_unchecked, from_c_str, ParseBoolError};
81 pub use unicode::str::{Words, Graphemes, GraphemeIndices};
82 pub use core::str::Pattern;
83 pub use core::str::{Searcher, ReverseSearcher, DoubleEndedSearcher, SearchStep};
86 Section: Creating a string
89 impl<S: Str> SliceConcatExt<str, String> for [S] {
90 fn concat(&self) -> String {
91 let s = self.as_slice();
97 // `len` calculation may overflow but push_str will check boundaries
98 let len = s.iter().map(|s| s.as_slice().len()).sum();
99 let mut result = String::with_capacity(len);
102 result.push_str(s.as_slice())
108 fn connect(&self, sep: &str) -> String {
109 let s = self.as_slice();
112 return String::new();
120 // this is wrong without the guarantee that `self` is non-empty
121 // `len` calculation may overflow but push_str but will check boundaries
122 let len = sep.len() * (s.len() - 1)
123 + s.iter().map(|s| s.as_slice().len()).sum();
124 let mut result = String::with_capacity(len);
125 let mut first = true;
131 result.push_str(sep);
133 result.push_str(s.as_slice());
143 // Helper functions used for Unicode normalization
144 fn canonical_sort(comb: &mut [(char, u8)]) {
145 let len = comb.len();
147 let mut swapped = false;
149 let class_a = comb[j-1].1;
150 let class_b = comb[j].1;
151 if class_a != 0 && class_b != 0 && class_a > class_b {
156 if !swapped { break; }
161 enum DecompositionType {
166 /// External iterator for a string decomposition's characters.
168 /// For use with the `std::iter` module.
170 #[unstable(feature = "unicode",
171 reason = "this functionality may be replaced with a more generic \
172 unicode crate on crates.io")]
173 pub struct Decompositions<'a> {
174 kind: DecompositionType,
176 buffer: Vec<(char, u8)>,
180 #[stable(feature = "rust1", since = "1.0.0")]
181 impl<'a> Iterator for Decompositions<'a> {
185 fn next(&mut self) -> Option<char> {
186 match self.buffer.first() {
189 self.buffer.remove(0);
192 Some(&(c, _)) if self.sorted => {
193 self.buffer.remove(0);
196 _ => self.sorted = false
200 for ch in self.iter.by_ref() {
201 let buffer = &mut self.buffer;
202 let sorted = &mut self.sorted;
206 unicode::char::canonical_combining_class(d);
207 if class == 0 && !*sorted {
208 canonical_sort(buffer);
211 buffer.push((d, class));
215 unicode::char::decompose_canonical(ch, callback)
218 unicode::char::decompose_compatible(ch, callback)
229 canonical_sort(&mut self.buffer);
233 if self.buffer.is_empty() {
236 match self.buffer.remove(0) {
246 fn size_hint(&self) -> (usize, Option<usize>) {
247 let (lower, _) = self.iter.size_hint();
253 enum RecompositionState {
259 /// External iterator for a string recomposition's characters.
261 /// For use with the `std::iter` module.
263 #[unstable(feature = "unicode",
264 reason = "this functionality may be replaced with a more generic \
265 unicode crate on crates.io")]
266 pub struct Recompositions<'a> {
267 iter: Decompositions<'a>,
268 state: RecompositionState,
269 buffer: VecDeque<char>,
270 composee: Option<char>,
274 #[stable(feature = "rust1", since = "1.0.0")]
275 impl<'a> Iterator for Recompositions<'a> {
279 fn next(&mut self) -> Option<char> {
283 for ch in self.iter.by_ref() {
284 let ch_class = unicode::char::canonical_combining_class(ch);
285 if self.composee.is_none() {
289 self.composee = Some(ch);
292 let k = self.composee.clone().unwrap();
294 match self.last_ccc {
296 match unicode::char::compose(k, ch) {
298 self.composee = Some(r);
303 self.composee = Some(ch);
306 self.buffer.push_back(ch);
307 self.last_ccc = Some(ch_class);
312 if l_class >= ch_class {
313 // `ch` is blocked from `composee`
315 self.composee = Some(ch);
316 self.last_ccc = None;
317 self.state = Purging;
320 self.buffer.push_back(ch);
321 self.last_ccc = Some(ch_class);
324 match unicode::char::compose(k, ch) {
326 self.composee = Some(r);
330 self.buffer.push_back(ch);
331 self.last_ccc = Some(ch_class);
337 self.state = Finished;
338 if self.composee.is_some() {
339 return self.composee.take();
343 match self.buffer.pop_front() {
344 None => self.state = Composing,
349 match self.buffer.pop_front() {
350 None => return self.composee.take(),
359 /// External iterator for a string's UTF16 codeunits.
361 /// For use with the `std::iter` module.
363 #[unstable(feature = "collections")]
364 pub struct Utf16Units<'a> {
365 encoder: Utf16Encoder<Chars<'a>>
368 #[stable(feature = "rust1", since = "1.0.0")]
369 impl<'a> Iterator for Utf16Units<'a> {
373 fn next(&mut self) -> Option<u16> { self.encoder.next() }
376 fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
383 // Return the initial codepoint accumulator for the first byte.
384 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
385 // for width 3, and 3 bits for width 4
386 macro_rules! utf8_first_byte {
387 ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
390 // return the value of $ch updated with continuation byte $byte
391 macro_rules! utf8_acc_cont_byte {
392 ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
395 #[stable(feature = "rust1", since = "1.0.0")]
396 impl Borrow<str> for String {
397 fn borrow(&self) -> &str { &self[..] }
400 #[stable(feature = "rust1", since = "1.0.0")]
401 impl ToOwned for str {
403 fn to_owned(&self) -> String {
405 String::from_utf8_unchecked(self.as_bytes().to_owned())
415 Section: Trait implementations
419 /// Any string that can be represented as a slice.
422 #[stable(feature = "rust1", since = "1.0.0")]
424 /// Escapes each char in `s` with `char::escape_default`.
425 #[unstable(feature = "collections",
426 reason = "return type may change to be an iterator")]
427 pub fn escape_default(&self) -> String {
428 self.chars().flat_map(|c| c.escape_default()).collect()
431 /// Escapes each char in `s` with `char::escape_unicode`.
432 #[unstable(feature = "collections",
433 reason = "return type may change to be an iterator")]
434 pub fn escape_unicode(&self) -> String {
435 self.chars().flat_map(|c| c.escape_unicode()).collect()
438 /// Replaces all occurrences of one string with another.
440 /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a second `&str` to
441 /// replace it with. If the original `&str` isn't found, no change occurs.
446 /// let s = "this is old";
448 /// assert_eq!(s.replace("old", "new"), "this is new");
451 /// When a `&str` isn't found:
454 /// let s = "this is old";
455 /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub fn replace(&self, from: &str, to: &str) -> String {
459 let mut result = String::new();
460 let mut last_end = 0;
461 for (start, end) in self.match_indices(from) {
462 result.push_str(unsafe { self.slice_unchecked(last_end, start) });
466 result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
470 /// Returns an iterator over the string in Unicode Normalization Form D
471 /// (canonical decomposition).
473 #[unstable(feature = "unicode",
474 reason = "this functionality may be replaced with a more generic \
475 unicode crate on crates.io")]
476 pub fn nfd_chars(&self) -> Decompositions {
478 iter: self[..].chars(),
485 /// Returns an iterator over the string in Unicode Normalization Form KD
486 /// (compatibility decomposition).
488 #[unstable(feature = "unicode",
489 reason = "this functionality may be replaced with a more generic \
490 unicode crate on crates.io")]
491 pub fn nfkd_chars(&self) -> Decompositions {
493 iter: self[..].chars(),
500 /// An Iterator over the string in Unicode Normalization Form C
501 /// (canonical decomposition followed by canonical composition).
503 #[unstable(feature = "unicode",
504 reason = "this functionality may be replaced with a more generic \
505 unicode crate on crates.io")]
506 pub fn nfc_chars(&self) -> Recompositions {
508 iter: self.nfd_chars(),
510 buffer: VecDeque::new(),
516 /// An Iterator over the string in Unicode Normalization Form KC
517 /// (compatibility decomposition followed by canonical composition).
519 #[unstable(feature = "unicode",
520 reason = "this functionality may be replaced with a more generic \
521 unicode crate on crates.io")]
522 pub fn nfkc_chars(&self) -> Recompositions {
524 iter: self.nfkd_chars(),
526 buffer: VecDeque::new(),
532 /// Returns `true` if `self` contains another `&str`.
537 /// assert!("bananas".contains("nana"));
539 /// assert!(!"bananas".contains("foobar"));
541 #[stable(feature = "rust1", since = "1.0.0")]
542 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
543 core_str::StrExt::contains(&self[..], pat)
546 /// Returns `true` if `self` contains a `char`.
551 /// assert!("hello".contains_char('e'));
553 /// assert!(!"hello".contains_char('z'));
555 #[unstable(feature = "collections")]
556 #[deprecated(since = "1.0.0", reason = "use `contains()` with a char")]
557 pub fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
558 core_str::StrExt::contains_char(&self[..], pat)
561 /// An iterator over the codepoints of `self`.
566 /// let v: Vec<char> = "abc åäö".chars().collect();
568 /// assert_eq!(v, ['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
570 #[stable(feature = "rust1", since = "1.0.0")]
571 pub fn chars(&self) -> Chars {
572 core_str::StrExt::chars(&self[..])
575 /// An iterator over the bytes of `self`.
580 /// let v: Vec<u8> = "bors".bytes().collect();
582 /// assert_eq!(v, b"bors".to_vec());
584 #[stable(feature = "rust1", since = "1.0.0")]
585 pub fn bytes(&self) -> Bytes {
586 core_str::StrExt::bytes(&self[..])
589 /// An iterator over the characters of `self` and their byte offsets.
594 /// let v: Vec<(usize, char)> = "abc".char_indices().collect();
595 /// let b = vec![(0, 'a'), (1, 'b'), (2, 'c')];
597 /// assert_eq!(v, b);
599 #[stable(feature = "rust1", since = "1.0.0")]
600 pub fn char_indices(&self) -> CharIndices {
601 core_str::StrExt::char_indices(&self[..])
604 /// An iterator over substrings of `self`, separated by characters
605 /// matched by a pattern.
607 /// The pattern can be a simple `&str`, or a closure that determines
612 /// Simple `&str` patterns:
615 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
616 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
618 /// let v: Vec<&str> = "".split('X').collect();
619 /// assert_eq!(v, [""]);
622 /// More complex patterns with a lambda:
625 /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
626 /// assert_eq!(v, ["abc", "def", "ghi"]);
628 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
629 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
633 core_str::StrExt::split(&self[..], pat)
636 /// An iterator over substrings of `self`, separated by characters matched by a pattern,
637 /// restricted to splitting at most `count` times.
639 /// The pattern can be a simple `&str`, or a closure that determines
644 /// Simple `&str` patterns:
647 /// let v: Vec<&str> = "Mary had a little lambda".splitn(2, ' ').collect();
648 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
650 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(2, 'X').collect();
651 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
653 /// let v: Vec<&str> = "abcXdef".splitn(0, 'X').collect();
654 /// assert_eq!(v, ["abcXdef"]);
656 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
657 /// assert_eq!(v, [""]);
660 /// More complex patterns with a lambda:
663 /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |c: char| c.is_numeric()).collect();
664 /// assert_eq!(v, ["abc", "def2ghi"]);
666 #[stable(feature = "rust1", since = "1.0.0")]
667 pub fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
668 core_str::StrExt::splitn(&self[..], count, pat)
671 /// An iterator over substrings of `self`, separated by characters
672 /// matched by a pattern.
674 /// Equivalent to `split`, except that the trailing substring is skipped if empty.
676 /// The pattern can be a simple `&str`, or a closure that determines
681 /// Simple `&str` patterns:
684 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
685 /// assert_eq!(v, ["A", "B"]);
687 /// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
688 /// assert_eq!(v, ["A", "", "B", ""]);
691 /// More complex patterns with a lambda:
694 /// let v: Vec<&str> = "abc1def2ghi3".split_terminator(|c: char| c.is_numeric()).collect();
695 /// assert_eq!(v, ["abc", "def", "ghi"]);
697 #[stable(feature = "rust1", since = "1.0.0")]
698 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
699 core_str::StrExt::split_terminator(&self[..], pat)
702 /// An iterator over substrings of `self`, separated by a pattern,
703 /// starting from the end of the string.
710 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
711 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
713 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
714 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
717 /// More complex patterns with a lambda:
720 /// let v: Vec<&str> = "abc1def2ghi".rsplit(|c: char| c.is_numeric()).collect();
721 /// assert_eq!(v, ["ghi", "def", "abc"]);
723 #[stable(feature = "rust1", since = "1.0.0")]
724 pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
725 where P::Searcher: ReverseSearcher<'a>
727 core_str::StrExt::rsplit(&self[..], pat)
730 /// An iterator over substrings of `self`, separated by characters matched by a pattern,
731 /// starting from the end of the string.
733 /// Restricted to splitting at most `count` times.
735 /// The pattern can be a simple `&str`, or a closure that determines the split.
739 /// Simple `&str` patterns:
742 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
743 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
745 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(2, 'X').collect();
746 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
749 /// More complex patterns with a lambda:
752 /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |c: char| c.is_numeric()).collect();
753 /// assert_eq!(v, ["ghi", "abc1def"]);
755 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P> {
757 core_str::StrExt::rsplitn(&self[..], count, pat)
760 /// An iterator over the start and end indices of the disjoint matches of a `&str` within
763 /// That is, each returned value `(start, end)` satisfies `self.slice(start, end) == sep`. For
764 /// matches of `sep` within `self` that overlap, only the indices corresponding to the first
765 /// match are returned.
770 /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
771 /// assert_eq!(v, [(0,3), (6,9), (12,15)]);
773 /// let v: Vec<(usize, usize)> = "1abcabc2".match_indices("abc").collect();
774 /// assert_eq!(v, [(1,4), (4,7)]);
776 /// let v: Vec<(usize, usize)> = "ababa".match_indices("aba").collect();
777 /// assert_eq!(v, [(0, 3)]); // only the first `aba`
779 #[unstable(feature = "collections",
780 reason = "might have its iterator type changed")]
781 // NB: Right now MatchIndices yields `(usize, usize)`,
782 // but it would be more consistent and useful to return `(usize, &str)`
783 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
784 core_str::StrExt::match_indices(&self[..], pat)
787 /// An iterator over the substrings of `self` separated by a `&str`.
792 /// let v: Vec<&str> = "abcXXXabcYYYabc".split_str("abc").collect();
793 /// assert_eq!(v, ["", "XXX", "YYY", ""]);
795 /// let v: Vec<&str> = "1abcabc2".split_str("abc").collect();
796 /// assert_eq!(v, ["1", "", "2"]);
798 #[unstable(feature = "collections")]
799 #[deprecated(since = "1.0.0", reason = "use `split()` with a `&str`")]
800 #[allow(deprecated) /* for SplitStr */]
801 pub fn split_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitStr<'a, P> {
802 core_str::StrExt::split_str(&self[..], pat)
805 /// An iterator over the lines of a string, separated by `\n`.
807 /// This does not include the empty string after a trailing `\n`.
812 /// let four_lines = "foo\nbar\n\nbaz";
813 /// let v: Vec<&str> = four_lines.lines().collect();
815 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
818 /// Leaving off the trailing character:
821 /// let four_lines = "foo\nbar\n\nbaz\n";
822 /// let v: Vec<&str> = four_lines.lines().collect();
824 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
826 #[stable(feature = "rust1", since = "1.0.0")]
827 pub fn lines(&self) -> Lines {
828 core_str::StrExt::lines(&self[..])
831 /// An iterator over the lines of a string, separated by either `\n` or `\r\n`.
833 /// As with `.lines()`, this does not include an empty trailing line.
838 /// let four_lines = "foo\r\nbar\n\r\nbaz";
839 /// let v: Vec<&str> = four_lines.lines_any().collect();
841 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
844 /// Leaving off the trailing character:
847 /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
848 /// let v: Vec<&str> = four_lines.lines_any().collect();
850 /// assert_eq!(v, ["foo", "bar", "", "baz"]);
852 #[stable(feature = "rust1", since = "1.0.0")]
853 pub fn lines_any(&self) -> LinesAny {
854 core_str::StrExt::lines_any(&self[..])
857 /// Deprecated: use `s[a .. b]` instead.
858 #[unstable(feature = "collections",
859 reason = "use slice notation [a..b] instead")]
860 #[deprecated(since = "1.0.0", reason = "use slice notation [a..b] instead")]
861 pub fn slice(&self, begin: usize, end: usize) -> &str {
865 /// Deprecated: use `s[a..]` instead.
866 #[unstable(feature = "collections",
867 reason = "use slice notation [a..b] instead")]
868 #[deprecated(since = "1.0.0", reason = "use slice notation [a..] instead")]
869 pub fn slice_from(&self, begin: usize) -> &str {
873 /// Deprecated: use `s[..a]` instead.
874 #[unstable(feature = "collections",
875 reason = "use slice notation [a..b] instead")]
876 #[deprecated(since = "1.0.0", reason = "use slice notation [..a] instead")]
877 pub fn slice_to(&self, end: usize) -> &str {
881 /// Returns a slice of the string from the character range [`begin`..`end`).
883 /// That is, start at the `begin`-th code point of the string and continue
884 /// to the `end`-th code point. This does not detect or handle edge cases
885 /// such as leaving a combining character as the first code point of the
888 /// Due to the design of UTF-8, this operation is `O(end)`. See `slice`,
889 /// `slice_to` and `slice_from` for `O(1)` variants that use byte indices
890 /// rather than code point indices.
894 /// Panics if `begin` > `end` or the either `begin` or `end` are beyond the
895 /// last character of the string.
900 /// let s = "Löwe 老虎 Léopard";
902 /// assert_eq!(s.slice_chars(0, 4), "Löwe");
903 /// assert_eq!(s.slice_chars(5, 7), "老虎");
905 #[unstable(feature = "collections",
906 reason = "may have yet to prove its worth")]
907 pub fn slice_chars(&self, begin: usize, end: usize) -> &str {
908 core_str::StrExt::slice_chars(&self[..], begin, end)
911 /// Takes a bytewise slice from a string.
913 /// Returns the substring from [`begin`..`end`).
917 /// Caller must check both UTF-8 character boundaries and the boundaries of the entire slice as
923 /// let s = "Löwe 老虎 Léopard";
926 /// assert_eq!(s.slice_unchecked(0, 21), "Löwe 老虎 Léopard");
929 #[stable(feature = "rust1", since = "1.0.0")]
930 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
931 core_str::StrExt::slice_unchecked(&self[..], begin, end)
934 /// Returns `true` if the given `&str` is a prefix of the string.
939 /// assert!("banana".starts_with("ba"));
941 #[stable(feature = "rust1", since = "1.0.0")]
942 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
943 core_str::StrExt::starts_with(&self[..], pat)
946 /// Returns true if the given `&str` is a suffix of the string.
951 /// assert!("banana".ends_with("nana"));
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
955 where P::Searcher: ReverseSearcher<'a>
957 core_str::StrExt::ends_with(&self[..], pat)
960 /// Returns a string with all pre- and suffixes that match a pattern repeatedly removed.
962 /// The pattern can be a simple `&str`, or a closure that determines the split.
966 /// Simple `&str` patterns:
969 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
971 /// let x: &[_] = &['1', '2'];
972 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
975 /// More complex patterns with a lambda:
978 /// assert_eq!("123foo1bar123".trim_matches(|c: char| c.is_numeric()), "foo1bar");
980 #[stable(feature = "rust1", since = "1.0.0")]
981 pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
982 where P::Searcher: DoubleEndedSearcher<'a>
984 core_str::StrExt::trim_matches(&self[..], pat)
987 /// Returns a string with all prefixes that match a pattern repeatedly removed.
989 /// The pattern can be a simple `&str`, or a closure that determines the split.
993 /// Simple `&str` patterns:
996 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
998 /// let x: &[_] = &['1', '2'];
999 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1002 /// More complex patterns with a lambda:
1005 /// assert_eq!("123foo1bar123".trim_left_matches(|c: char| c.is_numeric()), "foo1bar123");
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1009 core_str::StrExt::trim_left_matches(&self[..], pat)
1012 /// Returns a string with all suffixes that match a pattern repeatedly removed.
1014 /// The pattern can be a simple `&str`, or a closure that determines the split.
1018 /// Simple `&str` patterns:
1021 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1022 /// let x: &[_] = &['1', '2'];
1023 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1026 /// More complex patterns with a lambda:
1029 /// assert_eq!("123foo1bar123".trim_right_matches(|c: char| c.is_numeric()), "123foo1bar");
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1033 where P::Searcher: ReverseSearcher<'a>
1035 core_str::StrExt::trim_right_matches(&self[..], pat)
1038 /// Check that `index`-th byte lies at the start and/or end of a UTF-8 code point sequence.
1040 /// The start and end of the string (when `index == self.len()`) are considered to be
1045 /// Panics if `index` is greater than `self.len()`.
1050 /// let s = "Löwe 老虎 Léopard";
1051 /// assert!(s.is_char_boundary(0));
1053 /// assert!(s.is_char_boundary(6));
1054 /// assert!(s.is_char_boundary(s.len()));
1056 /// // second byte of `ö`
1057 /// assert!(!s.is_char_boundary(2));
1059 /// // third byte of `老`
1060 /// assert!(!s.is_char_boundary(8));
1062 #[unstable(feature = "str_char",
1063 reason = "it is unclear whether this method pulls its weight \
1064 with the existence of the char_indices iterator or \
1065 this method may want to be replaced with checked \
1067 pub fn is_char_boundary(&self, index: usize) -> bool {
1068 core_str::StrExt::is_char_boundary(&self[..], index)
1071 /// Given a byte position, return the next char and its index.
1073 /// This can be used to iterate over the Unicode characters of a string.
1077 /// If `i` is greater than or equal to the length of the string.
1078 /// If `i` is not the index of the beginning of a valid UTF-8 character.
1082 /// This example manually iterates through the characters of a string; this should normally be
1083 /// done by `.chars()` or `.char_indices()`.
1086 /// use std::str::CharRange;
1088 /// let s = "中华Việt Nam";
1090 /// while i < s.len() {
1091 /// let CharRange {ch, next} = s.char_range_at(i);
1092 /// println!("{}: {}", i, ch);
1111 #[unstable(feature = "str_char",
1112 reason = "often replaced by char_indices, this method may \
1113 be removed in favor of just char_at() or eventually \
1114 removed altogether")]
1115 pub fn char_range_at(&self, start: usize) -> CharRange {
1116 core_str::StrExt::char_range_at(&self[..], start)
1119 /// Given a byte position, return the previous `char` and its position.
1121 /// This function can be used to iterate over a Unicode string in reverse.
1123 /// Returns 0 for next index if called on start index 0.
1127 /// If `i` is greater than the length of the string.
1128 /// If `i` is not an index following a valid UTF-8 character.
1132 /// This example manually iterates through the characters of a string; this should normally be
1133 /// done by `.chars().rev()` or `.char_indices()`.
1136 /// use std::str::CharRange;
1138 /// let s = "中华Việt Nam";
1139 /// let mut i = s.len();
1141 /// let CharRange {ch, next} = s.char_range_at_reverse(i);
1142 /// println!("{}: {}", i, ch);
1161 #[unstable(feature = "str_char",
1162 reason = "often replaced by char_indices, this method may \
1163 be removed in favor of just char_at_reverse() or \
1164 eventually removed altogether")]
1165 pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
1166 core_str::StrExt::char_range_at_reverse(&self[..], start)
1169 /// Given a byte position, return the `char` at that position.
1173 /// If `i` is greater than or equal to the length of the string.
1174 /// If `i` is not the index of the beginning of a valid UTF-8 character.
1180 /// assert_eq!(s.char_at(1), 'b');
1181 /// assert_eq!(s.char_at(2), 'π');
1183 #[unstable(feature = "str_char",
1184 reason = "frequently replaced by the chars() iterator, this \
1185 method may be removed or possibly renamed in the \
1186 future; it is normally replaced by chars/char_indices \
1187 iterators or by getting the first char from a \
1189 pub fn char_at(&self, i: usize) -> char {
1190 core_str::StrExt::char_at(&self[..], i)
1193 /// Given a byte position, return the `char` at that position, counting from the end.
1197 /// If `i` is greater than the length of the string.
1198 /// If `i` is not an index following a valid UTF-8 character.
1204 /// assert_eq!(s.char_at_reverse(1), 'a');
1205 /// assert_eq!(s.char_at_reverse(2), 'b');
1207 #[unstable(feature = "str_char",
1208 reason = "see char_at for more details, but reverse semantics \
1209 are also somewhat unclear, especially with which \
1210 cases generate panics")]
1211 pub fn char_at_reverse(&self, i: usize) -> char {
1212 core_str::StrExt::char_at_reverse(&self[..], i)
1215 /// Convert `self` to a byte slice.
1220 /// assert_eq!("bors".as_bytes(), b"bors");
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 pub fn as_bytes(&self) -> &[u8] {
1224 core_str::StrExt::as_bytes(&self[..])
1227 /// Returns the byte index of the first character of `self` that matches the pattern, if it
1230 /// Returns `None` if it doesn't exist.
1232 /// The pattern can be a simple `&str`, or a closure that determines the split.
1236 /// Simple `&str` patterns:
1239 /// let s = "Löwe 老虎 Léopard";
1241 /// assert_eq!(s.find('L'), Some(0));
1242 /// assert_eq!(s.find('é'), Some(14));
1246 /// More complex patterns with a lambda:
1249 /// let s = "Löwe 老虎 Léopard";
1251 /// assert_eq!(s.find(|c: char| c.is_whitespace()), Some(5));
1254 /// Not finding the pattern:
1257 /// let s = "Löwe 老虎 Léopard";
1258 /// let x: &[_] = &['1', '2'];
1260 /// assert_eq!(s.find(x), None);
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1264 core_str::StrExt::find(&self[..], pat)
1267 /// Returns the byte index of the last character of `self` that matches the pattern, if it
1270 /// Returns `None` if it doesn't exist.
1272 /// The pattern can be a simple `&str`, or a closure that determines the split.
1276 /// Simple `&str` patterns:
1279 /// let s = "Löwe 老虎 Léopard";
1281 /// assert_eq!(s.rfind('L'), Some(13));
1282 /// assert_eq!(s.rfind('é'), Some(14));
1285 /// More complex patterns with a lambda:
1288 /// let s = "Löwe 老虎 Léopard";
1290 /// assert_eq!(s.rfind(|c: char| c.is_whitespace()), Some(12));
1293 /// Not finding the pattern:
1296 /// let s = "Löwe 老虎 Léopard";
1297 /// let x: &[_] = &['1', '2'];
1299 /// assert_eq!(s.rfind(x), None);
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
1303 where P::Searcher: ReverseSearcher<'a>
1305 core_str::StrExt::rfind(&self[..], pat)
1308 /// Returns the byte index of the first matching substring if it exists.
1310 /// Returns `None` if it doesn't exist.
1312 /// The pattern can be a simple `&str`, or a closure that determines the split.
1317 /// let s = "Löwe 老虎 Léopard";
1319 /// assert_eq!(s.find_str("老虎 L"), Some(6));
1320 /// assert_eq!(s.find_str("muffin man"), None);
1322 #[unstable(feature = "collections")]
1323 #[deprecated(since = "1.0.0", reason = "use `find()` with a `&str`")]
1324 pub fn find_str<'a, P: Pattern<'a>>(&'a self, needle: P) -> Option<usize> {
1325 core_str::StrExt::find_str(&self[..], needle)
1328 /// Retrieves the first character from a `&str` and returns it.
1330 /// This does not allocate a new string; instead, it returns a slice that points one character
1331 /// beyond the character that was shifted.
1333 /// If the slice does not contain any characters, None is returned instead.
1338 /// let s = "Löwe 老虎 Léopard";
1339 /// let (c, s1) = s.slice_shift_char().unwrap();
1341 /// assert_eq!(c, 'L');
1342 /// assert_eq!(s1, "öwe 老虎 Léopard");
1344 /// let (c, s2) = s1.slice_shift_char().unwrap();
1346 /// assert_eq!(c, 'ö');
1347 /// assert_eq!(s2, "we 老虎 Léopard");
1349 #[unstable(feature = "str_char",
1350 reason = "awaiting conventions about shifting and slices and \
1351 may not be warranted with the existence of the chars \
1352 and/or char_indices iterators")]
1353 pub fn slice_shift_char(&self) -> Option<(char, &str)> {
1354 core_str::StrExt::slice_shift_char(&self[..])
1357 /// Returns the byte offset of an inner slice relative to an enclosing outer slice.
1361 /// Panics if `inner` is not a direct slice contained within self.
1366 /// let string = "a\nb\nc";
1367 /// let lines: Vec<&str> = string.lines().collect();
1369 /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
1370 /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
1371 /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
1373 #[unstable(feature = "collections",
1374 reason = "awaiting convention about comparability of arbitrary slices")]
1375 pub fn subslice_offset(&self, inner: &str) -> usize {
1376 core_str::StrExt::subslice_offset(&self[..], inner)
1379 /// Return an unsafe pointer to the `&str`'s buffer.
1381 /// The caller must ensure that the string outlives this pointer, and that it is not
1382 /// reallocated (e.g. by pushing to the string).
1387 /// let s = "Hello";
1388 /// let p = s.as_ptr();
1390 #[stable(feature = "rust1", since = "1.0.0")]
1392 pub fn as_ptr(&self) -> *const u8 {
1393 core_str::StrExt::as_ptr(&self[..])
1396 /// Return an iterator of `u16` over the string encoded as UTF-16.
1397 #[unstable(feature = "collections",
1398 reason = "this functionality may only be provided by libunicode")]
1399 pub fn utf16_units(&self) -> Utf16Units {
1400 Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
1403 /// Returns the length of `self` in bytes.
1408 /// assert_eq!("foo".len(), 3);
1409 /// assert_eq!("ƒoo".len(), 4); // fancy f!
1411 #[stable(feature = "rust1", since = "1.0.0")]
1413 pub fn len(&self) -> usize {
1414 core_str::StrExt::len(&self[..])
1417 /// Returns true if this slice has a length of zero bytes.
1422 /// assert!("".is_empty());
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 pub fn is_empty(&self) -> bool {
1427 core_str::StrExt::is_empty(&self[..])
1430 /// Parses `self` into the specified type.
1434 /// Will return `Err` if it's not possible to parse `self` into the type.
1439 /// assert_eq!("4".parse::<u32>(), Ok(4));
1445 /// assert!("j".parse::<u32>().is_err());
1448 #[stable(feature = "rust1", since = "1.0.0")]
1449 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1450 core_str::StrExt::parse(&self[..])
1453 /// Returns an iterator over the [grapheme clusters][graphemes] of `self`.
1455 /// [graphemes]: http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
1457 /// If `is_extended` is true, the iterator is over the *extended grapheme clusters*;
1458 /// otherwise, the iterator is over the *legacy grapheme clusters*.
1459 /// [UAX#29](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
1460 /// recommends extended grapheme cluster boundaries for general processing.
1465 /// let gr1 = "a\u{310}e\u{301}o\u{308}\u{332}".graphemes(true).collect::<Vec<&str>>();
1466 /// let b: &[_] = &["a\u{310}", "e\u{301}", "o\u{308}\u{332}"];
1468 /// assert_eq!(gr1.as_slice(), b);
1470 /// let gr2 = "a\r\nb🇷🇺🇸🇹".graphemes(true).collect::<Vec<&str>>();
1471 /// let b: &[_] = &["a", "\r\n", "b", "🇷🇺🇸🇹"];
1473 /// assert_eq!(gr2.as_slice(), b);
1475 #[unstable(feature = "unicode",
1476 reason = "this functionality may only be provided by libunicode")]
1477 pub fn graphemes(&self, is_extended: bool) -> Graphemes {
1478 UnicodeStr::graphemes(&self[..], is_extended)
1481 /// Returns an iterator over the grapheme clusters of `self` and their byte offsets. See
1482 /// `graphemes()` for more information.
1487 /// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(usize, &str)>>();
1488 /// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
1490 /// assert_eq!(gr_inds.as_slice(), b);
1492 #[unstable(feature = "unicode",
1493 reason = "this functionality may only be provided by libunicode")]
1494 pub fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices {
1495 UnicodeStr::grapheme_indices(&self[..], is_extended)
1498 /// An iterator over the non-empty words of `self`.
1500 /// A 'word' is a subsequence separated by any sequence of whitespace. Sequences of whitespace
1501 /// are collapsed, so empty "words" are not included.
1506 /// let some_words = " Mary had\ta little \n\t lamb";
1507 /// let v: Vec<&str> = some_words.words().collect();
1509 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1511 #[unstable(feature = "str_words",
1512 reason = "the precise algorithm to use is unclear")]
1513 pub fn words(&self) -> Words {
1514 UnicodeStr::words(&self[..])
1517 /// Returns a string's displayed width in columns.
1519 /// Control characters have zero width.
1521 /// `is_cjk` determines behavior for characters in the Ambiguous category: if `is_cjk` is
1522 /// `true`, these are 2 columns wide; otherwise, they are 1. In CJK locales, `is_cjk` should be
1523 /// `true`, else it should be `false`.
1524 /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) recommends that these
1525 /// characters be treated as 1 column (i.e., `is_cjk = false`) if the locale is unknown.
1526 #[unstable(feature = "unicode",
1527 reason = "this functionality may only be provided by libunicode")]
1528 pub fn width(&self, is_cjk: bool) -> usize {
1529 UnicodeStr::width(&self[..], is_cjk)
1532 /// Returns a `&str` with leading and trailing whitespace removed.
1537 /// let s = " Hello\tworld\t";
1538 /// assert_eq!(s.trim(), "Hello\tworld");
1540 #[stable(feature = "rust1", since = "1.0.0")]
1541 pub fn trim(&self) -> &str {
1542 UnicodeStr::trim(&self[..])
1545 /// Returns a `&str` with leading whitespace removed.
1550 /// let s = " Hello\tworld\t";
1551 /// assert_eq!(s.trim_left(), "Hello\tworld\t");
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 pub fn trim_left(&self) -> &str {
1555 UnicodeStr::trim_left(&self[..])
1558 /// Returns a `&str` with trailing whitespace removed.
1563 /// let s = " Hello\tworld\t";
1564 /// assert_eq!(s.trim_right(), " Hello\tworld");
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 pub fn trim_right(&self) -> &str {
1568 UnicodeStr::trim_right(&self[..])
1571 /// Returns the lowercase equivalent of this string.
1575 /// let s = "HELLO";
1576 /// assert_eq!(s.to_lowercase(), "hello");
1577 #[unstable(feature = "collections")]
1578 pub fn to_lowercase(&self) -> String {
1579 let mut s = String::with_capacity(self.len());
1580 s.extend(self[..].chars().flat_map(|c| c.to_lowercase()));
1584 /// Returns the uppercase equivalent of this string.
1588 /// let s = "hello";
1589 /// assert_eq!(s.to_uppercase(), "HELLO");
1590 #[unstable(feature = "collections")]
1591 pub fn to_uppercase(&self) -> String {
1592 let mut s = String::with_capacity(self.len());
1593 s.extend(self[..].chars().flat_map(|c| c.to_uppercase()));