1 //! String manipulation.
3 //! For more details, see the [`std::str`] module.
5 //! [`std::str`]: ../../std/str/index.html
7 #![stable(feature = "rust1", since = "1.0.0")]
16 use self::pattern::Pattern;
17 use self::pattern::{DoubleEndedSearcher, ReverseSearcher, Searcher};
19 use crate::char::{self, EscapeDebugExtArgs};
21 use crate::slice::{self, SliceIndex};
25 #[unstable(feature = "str_internals", issue = "none")]
26 #[allow(missing_docs)]
29 #[stable(feature = "rust1", since = "1.0.0")]
30 pub use converts::{from_utf8, from_utf8_unchecked};
32 #[stable(feature = "str_mut_extras", since = "1.20.0")]
33 pub use converts::{from_utf8_mut, from_utf8_unchecked_mut};
35 #[stable(feature = "rust1", since = "1.0.0")]
36 pub use error::{ParseBoolError, Utf8Error};
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub use traits::FromStr;
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub use iter::{Bytes, CharIndices, Chars, Lines, SplitWhitespace};
44 #[stable(feature = "rust1", since = "1.0.0")]
46 pub use iter::LinesAny;
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub use iter::{RSplit, RSplitTerminator, Split, SplitTerminator};
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub use iter::{RSplitN, SplitN};
54 #[stable(feature = "str_matches", since = "1.2.0")]
55 pub use iter::{Matches, RMatches};
57 #[stable(feature = "str_match_indices", since = "1.5.0")]
58 pub use iter::{MatchIndices, RMatchIndices};
60 #[stable(feature = "encode_utf16", since = "1.8.0")]
61 pub use iter::EncodeUtf16;
63 #[stable(feature = "str_escape", since = "1.34.0")]
64 pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode};
66 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
67 pub use iter::SplitAsciiWhitespace;
69 #[stable(feature = "split_inclusive", since = "1.51.0")]
70 pub use iter::SplitInclusive;
72 #[unstable(feature = "str_internals", issue = "none")]
73 pub use validations::{next_code_point, utf8_char_width};
75 use iter::MatchIndicesInternal;
76 use iter::SplitInternal;
77 use iter::{MatchesInternal, SplitNInternal};
82 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
83 const MAX_DISPLAY_LENGTH: usize = 256;
84 let trunc_len = s.floor_char_boundary(MAX_DISPLAY_LENGTH);
85 let s_trunc = &s[..trunc_len];
86 let ellipsis = if trunc_len < s.len() { "[...]" } else { "" };
89 if begin > s.len() || end > s.len() {
90 let oob_index = if begin > s.len() { begin } else { end };
91 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
97 "begin <= end ({} <= {}) when slicing `{}`{}",
104 // 3. character boundary
105 let index = if !s.is_char_boundary(begin) { begin } else { end };
106 // find the character
107 let char_start = s.floor_char_boundary(index);
108 // `char_start` must be less than len and a char boundary
109 let ch = s[char_start..].chars().next().unwrap();
110 let char_range = char_start..char_start + ch.len_utf8();
112 "byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
113 index, ch, char_range, s_trunc, ellipsis
120 /// Returns the length of `self`.
122 /// This length is in bytes, not [`char`]s or graphemes. In other words,
123 /// it might not be what a human considers the length of the string.
125 /// [`char`]: prim@char
132 /// let len = "foo".len();
133 /// assert_eq!(3, len);
135 /// assert_eq!("ƒoo".len(), 4); // fancy f!
136 /// assert_eq!("ƒoo".chars().count(), 3);
138 #[stable(feature = "rust1", since = "1.0.0")]
139 #[rustc_const_stable(feature = "const_str_len", since = "1.39.0")]
142 pub const fn len(&self) -> usize {
143 self.as_bytes().len()
146 /// Returns `true` if `self` has a length of zero bytes.
154 /// assert!(s.is_empty());
156 /// let s = "not empty";
157 /// assert!(!s.is_empty());
159 #[stable(feature = "rust1", since = "1.0.0")]
160 #[rustc_const_stable(feature = "const_str_is_empty", since = "1.39.0")]
163 pub const fn is_empty(&self) -> bool {
167 /// Checks that `index`-th byte is the first byte in a UTF-8 code point
168 /// sequence or the end of the string.
170 /// The start and end of the string (when `index == self.len()`) are
171 /// considered to be boundaries.
173 /// Returns `false` if `index` is greater than `self.len()`.
178 /// let s = "Löwe 老虎 Léopard";
179 /// assert!(s.is_char_boundary(0));
181 /// assert!(s.is_char_boundary(6));
182 /// assert!(s.is_char_boundary(s.len()));
184 /// // second byte of `ö`
185 /// assert!(!s.is_char_boundary(2));
187 /// // third byte of `老`
188 /// assert!(!s.is_char_boundary(8));
191 #[stable(feature = "is_char_boundary", since = "1.9.0")]
193 pub fn is_char_boundary(&self, index: usize) -> bool {
195 // Test for 0 explicitly so that it can optimize out the check
196 // easily and skip reading string data for that case.
197 // Note that optimizing `self.get(..index)` relies on this.
202 match self.as_bytes().get(index) {
203 // For `None` we have two options:
205 // - index == self.len()
206 // Empty strings are valid, so return true
207 // - index > self.len()
208 // In this case return false
210 // The check is placed exactly here, because it improves generated
211 // code on higher opt-levels. See PR #84751 for more details.
212 None => index == self.len(),
214 Some(&b) => b.is_utf8_char_boundary(),
218 /// Finds the closest `x` not exceeding `index` where `is_char_boundary(x)` is `true`.
220 /// This method can help you truncate a string so that it's still valid UTF-8, but doesn't
221 /// exceed a given number of bytes. Note that this is done purely at the character level
222 /// and can still visually split graphemes, even though the underlying characters aren't
223 /// split. For example, the emoji 🧑🔬 (scientist) could be split so that the string only
224 /// includes 🧑 (person) instead.
229 /// #![feature(round_char_boundary)]
230 /// let s = "❤️🧡💛💚💙💜";
231 /// assert_eq!(s.len(), 26);
232 /// assert!(!s.is_char_boundary(13));
234 /// let closest = s.floor_char_boundary(13);
235 /// assert_eq!(closest, 10);
236 /// assert_eq!(&s[..closest], "❤️🧡");
238 #[unstable(feature = "round_char_boundary", issue = "93743")]
240 pub fn floor_char_boundary(&self, index: usize) -> usize {
241 if index >= self.len() {
244 let lower_bound = index.saturating_sub(3);
245 let new_index = self.as_bytes()[lower_bound..=index]
247 .rposition(|b| b.is_utf8_char_boundary());
249 // SAFETY: we know that the character boundary will be within four bytes
250 unsafe { lower_bound + new_index.unwrap_unchecked() }
254 /// Finds the closest `x` not below `index` where `is_char_boundary(x)` is `true`.
256 /// This method is the natural complement to [`floor_char_boundary`]. See that method
257 /// for more details.
259 /// [`floor_char_boundary`]: str::floor_char_boundary
263 /// Panics if `index > self.len()`.
268 /// #![feature(round_char_boundary)]
269 /// let s = "❤️🧡💛💚💙💜";
270 /// assert_eq!(s.len(), 26);
271 /// assert!(!s.is_char_boundary(13));
273 /// let closest = s.ceil_char_boundary(13);
274 /// assert_eq!(closest, 14);
275 /// assert_eq!(&s[..closest], "❤️🧡💛");
277 #[unstable(feature = "round_char_boundary", issue = "93743")]
279 pub fn ceil_char_boundary(&self, index: usize) -> usize {
280 if index > self.len() {
281 slice_error_fail(self, index, index)
283 let upper_bound = Ord::min(index + 4, self.len());
284 self.as_bytes()[index..upper_bound]
286 .position(|b| b.is_utf8_char_boundary())
287 .map_or(upper_bound, |pos| pos + index)
291 /// Converts a string slice to a byte slice. To convert the byte slice back
292 /// into a string slice, use the [`from_utf8`] function.
299 /// let bytes = "bors".as_bytes();
300 /// assert_eq!(b"bors", bytes);
302 #[stable(feature = "rust1", since = "1.0.0")]
303 #[rustc_const_stable(feature = "str_as_bytes", since = "1.39.0")]
306 #[allow(unused_attributes)]
307 pub const fn as_bytes(&self) -> &[u8] {
308 // SAFETY: const sound because we transmute two types with the same layout
309 unsafe { mem::transmute(self) }
312 /// Converts a mutable string slice to a mutable byte slice.
316 /// The caller must ensure that the content of the slice is valid UTF-8
317 /// before the borrow ends and the underlying `str` is used.
319 /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
326 /// let mut s = String::from("Hello");
327 /// let bytes = unsafe { s.as_bytes_mut() };
329 /// assert_eq!(b"Hello", bytes);
335 /// let mut s = String::from("🗻∈🌏");
338 /// let bytes = s.as_bytes_mut();
346 /// assert_eq!("🍔∈🌏", s);
348 #[stable(feature = "str_mut_extras", since = "1.20.0")]
351 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
352 // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
353 // has the same layout as `&[u8]` (only libstd can make this guarantee).
354 // The pointer dereference is safe since it comes from a mutable reference which
355 // is guaranteed to be valid for writes.
356 unsafe { &mut *(self as *mut str as *mut [u8]) }
359 /// Converts a string slice to a raw pointer.
361 /// As string slices are a slice of bytes, the raw pointer points to a
362 /// [`u8`]. This pointer will be pointing to the first byte of the string
365 /// The caller must ensure that the returned pointer is never written to.
366 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
368 /// [`as_mut_ptr`]: str::as_mut_ptr
376 /// let ptr = s.as_ptr();
378 #[stable(feature = "rust1", since = "1.0.0")]
379 #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
382 pub const fn as_ptr(&self) -> *const u8 {
383 self as *const str as *const u8
386 /// Converts a mutable string slice to a raw pointer.
388 /// As string slices are a slice of bytes, the raw pointer points to a
389 /// [`u8`]. This pointer will be pointing to the first byte of the string
392 /// It is your responsibility to make sure that the string slice only gets
393 /// modified in a way that it remains valid UTF-8.
394 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
397 pub fn as_mut_ptr(&mut self) -> *mut u8 {
398 self as *mut str as *mut u8
401 /// Returns a subslice of `str`.
403 /// This is the non-panicking alternative to indexing the `str`. Returns
404 /// [`None`] whenever equivalent indexing operation would panic.
409 /// let v = String::from("🗻∈🌏");
411 /// assert_eq!(Some("🗻"), v.get(0..4));
413 /// // indices not on UTF-8 sequence boundaries
414 /// assert!(v.get(1..).is_none());
415 /// assert!(v.get(..8).is_none());
418 /// assert!(v.get(..42).is_none());
420 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
422 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
426 /// Returns a mutable subslice of `str`.
428 /// This is the non-panicking alternative to indexing the `str`. Returns
429 /// [`None`] whenever equivalent indexing operation would panic.
434 /// let mut v = String::from("hello");
435 /// // correct length
436 /// assert!(v.get_mut(0..5).is_some());
438 /// assert!(v.get_mut(..42).is_none());
439 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
441 /// assert_eq!("hello", v);
443 /// let s = v.get_mut(0..2);
444 /// let s = s.map(|s| {
445 /// s.make_ascii_uppercase();
448 /// assert_eq!(Some("HE"), s);
450 /// assert_eq!("HEllo", v);
452 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
454 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
458 /// Returns an unchecked subslice of `str`.
460 /// This is the unchecked alternative to indexing the `str`.
464 /// Callers of this function are responsible that these preconditions are
467 /// * The starting index must not exceed the ending index;
468 /// * Indexes must be within bounds of the original slice;
469 /// * Indexes must lie on UTF-8 sequence boundaries.
471 /// Failing that, the returned string slice may reference invalid memory or
472 /// violate the invariants communicated by the `str` type.
479 /// assert_eq!("🗻", v.get_unchecked(0..4));
480 /// assert_eq!("∈", v.get_unchecked(4..7));
481 /// assert_eq!("🌏", v.get_unchecked(7..11));
484 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
486 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
487 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
488 // the slice is dereferenceable because `self` is a safe reference.
489 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
490 unsafe { &*i.get_unchecked(self) }
493 /// Returns a mutable, unchecked subslice of `str`.
495 /// This is the unchecked alternative to indexing the `str`.
499 /// Callers of this function are responsible that these preconditions are
502 /// * The starting index must not exceed the ending index;
503 /// * Indexes must be within bounds of the original slice;
504 /// * Indexes must lie on UTF-8 sequence boundaries.
506 /// Failing that, the returned string slice may reference invalid memory or
507 /// violate the invariants communicated by the `str` type.
512 /// let mut v = String::from("🗻∈🌏");
514 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
515 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
516 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
519 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
521 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
522 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
523 // the slice is dereferenceable because `self` is a safe reference.
524 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
525 unsafe { &mut *i.get_unchecked_mut(self) }
528 /// Creates a string slice from another string slice, bypassing safety
531 /// This is generally not recommended, use with caution! For a safe
532 /// alternative see [`str`] and [`Index`].
534 /// [`Index`]: crate::ops::Index
536 /// This new slice goes from `begin` to `end`, including `begin` but
539 /// To get a mutable string slice instead, see the
540 /// [`slice_mut_unchecked`] method.
542 /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
546 /// Callers of this function are responsible that three preconditions are
549 /// * `begin` must not exceed `end`.
550 /// * `begin` and `end` must be byte positions within the string slice.
551 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
558 /// let s = "Löwe 老虎 Léopard";
561 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
564 /// let s = "Hello, world!";
567 /// assert_eq!("world", s.slice_unchecked(7, 12));
570 #[stable(feature = "rust1", since = "1.0.0")]
571 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
574 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
575 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
576 // the slice is dereferenceable because `self` is a safe reference.
577 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
578 unsafe { &*(begin..end).get_unchecked(self) }
581 /// Creates a string slice from another string slice, bypassing safety
583 /// This is generally not recommended, use with caution! For a safe
584 /// alternative see [`str`] and [`IndexMut`].
586 /// [`IndexMut`]: crate::ops::IndexMut
588 /// This new slice goes from `begin` to `end`, including `begin` but
591 /// To get an immutable string slice instead, see the
592 /// [`slice_unchecked`] method.
594 /// [`slice_unchecked`]: str::slice_unchecked
598 /// Callers of this function are responsible that three preconditions are
601 /// * `begin` must not exceed `end`.
602 /// * `begin` and `end` must be byte positions within the string slice.
603 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
604 #[stable(feature = "str_slice_mut", since = "1.5.0")]
605 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
607 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
608 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
609 // the slice is dereferenceable because `self` is a safe reference.
610 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
611 unsafe { &mut *(begin..end).get_unchecked_mut(self) }
614 /// Divide one string slice into two at an index.
616 /// The argument, `mid`, should be a byte offset from the start of the
617 /// string. It must also be on the boundary of a UTF-8 code point.
619 /// The two slices returned go from the start of the string slice to `mid`,
620 /// and from `mid` to the end of the string slice.
622 /// To get mutable string slices instead, see the [`split_at_mut`]
625 /// [`split_at_mut`]: str::split_at_mut
629 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
630 /// past the end of the last code point of the string slice.
637 /// let s = "Per Martin-Löf";
639 /// let (first, last) = s.split_at(3);
641 /// assert_eq!("Per", first);
642 /// assert_eq!(" Martin-Löf", last);
646 #[stable(feature = "str_split_at", since = "1.4.0")]
647 pub fn split_at(&self, mid: usize) -> (&str, &str) {
648 // is_char_boundary checks that the index is in [0, .len()]
649 if self.is_char_boundary(mid) {
650 // SAFETY: just checked that `mid` is on a char boundary.
651 unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) }
653 slice_error_fail(self, 0, mid)
657 /// Divide one mutable string slice into two at an index.
659 /// The argument, `mid`, should be a byte offset from the start of the
660 /// string. It must also be on the boundary of a UTF-8 code point.
662 /// The two slices returned go from the start of the string slice to `mid`,
663 /// and from `mid` to the end of the string slice.
665 /// To get immutable string slices instead, see the [`split_at`] method.
667 /// [`split_at`]: str::split_at
671 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
672 /// past the end of the last code point of the string slice.
679 /// let mut s = "Per Martin-Löf".to_string();
681 /// let (first, last) = s.split_at_mut(3);
682 /// first.make_ascii_uppercase();
683 /// assert_eq!("PER", first);
684 /// assert_eq!(" Martin-Löf", last);
686 /// assert_eq!("PER Martin-Löf", s);
690 #[stable(feature = "str_split_at", since = "1.4.0")]
691 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
692 // is_char_boundary checks that the index is in [0, .len()]
693 if self.is_char_boundary(mid) {
694 let len = self.len();
695 let ptr = self.as_mut_ptr();
696 // SAFETY: just checked that `mid` is on a char boundary.
699 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
700 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
704 slice_error_fail(self, 0, mid)
708 /// Returns an iterator over the [`char`]s of a string slice.
710 /// As a string slice consists of valid UTF-8, we can iterate through a
711 /// string slice by [`char`]. This method returns such an iterator.
713 /// It's important to remember that [`char`] represents a Unicode Scalar
714 /// Value, and might not match your idea of what a 'character' is. Iteration
715 /// over grapheme clusters may be what you actually want. This functionality
716 /// is not provided by Rust's standard library, check crates.io instead.
723 /// let word = "goodbye";
725 /// let count = word.chars().count();
726 /// assert_eq!(7, count);
728 /// let mut chars = word.chars();
730 /// assert_eq!(Some('g'), chars.next());
731 /// assert_eq!(Some('o'), chars.next());
732 /// assert_eq!(Some('o'), chars.next());
733 /// assert_eq!(Some('d'), chars.next());
734 /// assert_eq!(Some('b'), chars.next());
735 /// assert_eq!(Some('y'), chars.next());
736 /// assert_eq!(Some('e'), chars.next());
738 /// assert_eq!(None, chars.next());
741 /// Remember, [`char`]s might not match your intuition about characters:
743 /// [`char`]: prim@char
748 /// let mut chars = y.chars();
750 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
751 /// assert_eq!(Some('\u{0306}'), chars.next());
753 /// assert_eq!(None, chars.next());
755 #[stable(feature = "rust1", since = "1.0.0")]
757 pub fn chars(&self) -> Chars<'_> {
758 Chars { iter: self.as_bytes().iter() }
761 /// Returns an iterator over the [`char`]s of a string slice, and their
764 /// As a string slice consists of valid UTF-8, we can iterate through a
765 /// string slice by [`char`]. This method returns an iterator of both
766 /// these [`char`]s, as well as their byte positions.
768 /// The iterator yields tuples. The position is first, the [`char`] is
776 /// let word = "goodbye";
778 /// let count = word.char_indices().count();
779 /// assert_eq!(7, count);
781 /// let mut char_indices = word.char_indices();
783 /// assert_eq!(Some((0, 'g')), char_indices.next());
784 /// assert_eq!(Some((1, 'o')), char_indices.next());
785 /// assert_eq!(Some((2, 'o')), char_indices.next());
786 /// assert_eq!(Some((3, 'd')), char_indices.next());
787 /// assert_eq!(Some((4, 'b')), char_indices.next());
788 /// assert_eq!(Some((5, 'y')), char_indices.next());
789 /// assert_eq!(Some((6, 'e')), char_indices.next());
791 /// assert_eq!(None, char_indices.next());
794 /// Remember, [`char`]s might not match your intuition about characters:
796 /// [`char`]: prim@char
799 /// let yes = "y̆es";
801 /// let mut char_indices = yes.char_indices();
803 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
804 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
806 /// // note the 3 here - the last character took up two bytes
807 /// assert_eq!(Some((3, 'e')), char_indices.next());
808 /// assert_eq!(Some((4, 's')), char_indices.next());
810 /// assert_eq!(None, char_indices.next());
812 #[stable(feature = "rust1", since = "1.0.0")]
814 pub fn char_indices(&self) -> CharIndices<'_> {
815 CharIndices { front_offset: 0, iter: self.chars() }
818 /// An iterator over the bytes of a string slice.
820 /// As a string slice consists of a sequence of bytes, we can iterate
821 /// through a string slice by byte. This method returns such an iterator.
828 /// let mut bytes = "bors".bytes();
830 /// assert_eq!(Some(b'b'), bytes.next());
831 /// assert_eq!(Some(b'o'), bytes.next());
832 /// assert_eq!(Some(b'r'), bytes.next());
833 /// assert_eq!(Some(b's'), bytes.next());
835 /// assert_eq!(None, bytes.next());
837 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn bytes(&self) -> Bytes<'_> {
840 Bytes(self.as_bytes().iter().copied())
843 /// Splits a string slice by whitespace.
845 /// The iterator returned will return string slices that are sub-slices of
846 /// the original string slice, separated by any amount of whitespace.
848 /// 'Whitespace' is defined according to the terms of the Unicode Derived
849 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
850 /// instead, use [`split_ascii_whitespace`].
852 /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
859 /// let mut iter = "A few words".split_whitespace();
861 /// assert_eq!(Some("A"), iter.next());
862 /// assert_eq!(Some("few"), iter.next());
863 /// assert_eq!(Some("words"), iter.next());
865 /// assert_eq!(None, iter.next());
868 /// All kinds of whitespace are considered:
871 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
872 /// assert_eq!(Some("Mary"), iter.next());
873 /// assert_eq!(Some("had"), iter.next());
874 /// assert_eq!(Some("a"), iter.next());
875 /// assert_eq!(Some("little"), iter.next());
876 /// assert_eq!(Some("lamb"), iter.next());
878 /// assert_eq!(None, iter.next());
880 #[must_use = "this returns the split string as an iterator, \
881 without modifying the original"]
882 #[stable(feature = "split_whitespace", since = "1.1.0")]
884 pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
885 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
888 /// Splits a string slice by ASCII whitespace.
890 /// The iterator returned will return string slices that are sub-slices of
891 /// the original string slice, separated by any amount of ASCII whitespace.
893 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
895 /// [`split_whitespace`]: str::split_whitespace
902 /// let mut iter = "A few words".split_ascii_whitespace();
904 /// assert_eq!(Some("A"), iter.next());
905 /// assert_eq!(Some("few"), iter.next());
906 /// assert_eq!(Some("words"), iter.next());
908 /// assert_eq!(None, iter.next());
911 /// All kinds of ASCII whitespace are considered:
914 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
915 /// assert_eq!(Some("Mary"), iter.next());
916 /// assert_eq!(Some("had"), iter.next());
917 /// assert_eq!(Some("a"), iter.next());
918 /// assert_eq!(Some("little"), iter.next());
919 /// assert_eq!(Some("lamb"), iter.next());
921 /// assert_eq!(None, iter.next());
923 #[must_use = "this returns the split string as an iterator, \
924 without modifying the original"]
925 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
927 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
929 self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
930 SplitAsciiWhitespace { inner }
933 /// An iterator over the lines of a string, as string slices.
935 /// Lines are ended with either a newline (`\n`) or a carriage return with
936 /// a line feed (`\r\n`).
938 /// The final line ending is optional. A string that ends with a final line
939 /// ending will return the same lines as an otherwise identical string
940 /// without a final line ending.
947 /// let text = "foo\r\nbar\n\nbaz\n";
948 /// let mut lines = text.lines();
950 /// assert_eq!(Some("foo"), lines.next());
951 /// assert_eq!(Some("bar"), lines.next());
952 /// assert_eq!(Some(""), lines.next());
953 /// assert_eq!(Some("baz"), lines.next());
955 /// assert_eq!(None, lines.next());
958 /// The final line ending isn't required:
961 /// let text = "foo\nbar\n\r\nbaz";
962 /// let mut lines = text.lines();
964 /// assert_eq!(Some("foo"), lines.next());
965 /// assert_eq!(Some("bar"), lines.next());
966 /// assert_eq!(Some(""), lines.next());
967 /// assert_eq!(Some("baz"), lines.next());
969 /// assert_eq!(None, lines.next());
971 #[stable(feature = "rust1", since = "1.0.0")]
973 pub fn lines(&self) -> Lines<'_> {
974 Lines(self.split_terminator('\n').map(LinesAnyMap))
977 /// An iterator over the lines of a string.
978 #[stable(feature = "rust1", since = "1.0.0")]
979 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
982 pub fn lines_any(&self) -> LinesAny<'_> {
983 LinesAny(self.lines())
986 /// Returns an iterator of `u16` over the string encoded as UTF-16.
993 /// let text = "Zażółć gęślą jaźń";
995 /// let utf8_len = text.len();
996 /// let utf16_len = text.encode_utf16().count();
998 /// assert!(utf16_len <= utf8_len);
1000 #[must_use = "this returns the encoded string as an iterator, \
1001 without modifying the original"]
1002 #[stable(feature = "encode_utf16", since = "1.8.0")]
1003 pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
1004 EncodeUtf16 { chars: self.chars(), extra: 0 }
1007 /// Returns `true` if the given pattern matches a sub-slice of
1008 /// this string slice.
1010 /// Returns `false` if it does not.
1012 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1013 /// function or closure that determines if a character matches.
1015 /// [`char`]: prim@char
1016 /// [pattern]: self::pattern
1023 /// let bananas = "bananas";
1025 /// assert!(bananas.contains("nana"));
1026 /// assert!(!bananas.contains("apples"));
1028 #[stable(feature = "rust1", since = "1.0.0")]
1030 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1031 pat.is_contained_in(self)
1034 /// Returns `true` if the given pattern matches a prefix of this
1037 /// Returns `false` if it does not.
1039 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1040 /// function or closure that determines if a character matches.
1042 /// [`char`]: prim@char
1043 /// [pattern]: self::pattern
1050 /// let bananas = "bananas";
1052 /// assert!(bananas.starts_with("bana"));
1053 /// assert!(!bananas.starts_with("nana"));
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1057 pat.is_prefix_of(self)
1060 /// Returns `true` if the given pattern matches a suffix of this
1063 /// Returns `false` if it does not.
1065 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1066 /// function or closure that determines if a character matches.
1068 /// [`char`]: prim@char
1069 /// [pattern]: self::pattern
1076 /// let bananas = "bananas";
1078 /// assert!(bananas.ends_with("anas"));
1079 /// assert!(!bananas.ends_with("nana"));
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
1084 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1086 pat.is_suffix_of(self)
1089 /// Returns the byte index of the first character of this string slice that
1090 /// matches the pattern.
1092 /// Returns [`None`] if the pattern doesn't match.
1094 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1095 /// function or closure that determines if a character matches.
1097 /// [`char`]: prim@char
1098 /// [pattern]: self::pattern
1102 /// Simple patterns:
1105 /// let s = "Löwe 老虎 Léopard Gepardi";
1107 /// assert_eq!(s.find('L'), Some(0));
1108 /// assert_eq!(s.find('é'), Some(14));
1109 /// assert_eq!(s.find("pard"), Some(17));
1112 /// More complex patterns using point-free style and closures:
1115 /// let s = "Löwe 老虎 Léopard";
1117 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1118 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1119 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1120 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1123 /// Not finding the pattern:
1126 /// let s = "Löwe 老虎 Léopard";
1127 /// let x: &[_] = &['1', '2'];
1129 /// assert_eq!(s.find(x), None);
1131 #[stable(feature = "rust1", since = "1.0.0")]
1133 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1134 pat.into_searcher(self).next_match().map(|(i, _)| i)
1137 /// Returns the byte index for the first character of the rightmost match of the pattern in
1138 /// this string slice.
1140 /// Returns [`None`] if the pattern doesn't match.
1142 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1143 /// function or closure that determines if a character matches.
1145 /// [`char`]: prim@char
1146 /// [pattern]: self::pattern
1150 /// Simple patterns:
1153 /// let s = "Löwe 老虎 Léopard Gepardi";
1155 /// assert_eq!(s.rfind('L'), Some(13));
1156 /// assert_eq!(s.rfind('é'), Some(14));
1157 /// assert_eq!(s.rfind("pard"), Some(24));
1160 /// More complex patterns with closures:
1163 /// let s = "Löwe 老虎 Léopard";
1165 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1166 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1169 /// Not finding the pattern:
1172 /// let s = "Löwe 老虎 Léopard";
1173 /// let x: &[_] = &['1', '2'];
1175 /// assert_eq!(s.rfind(x), None);
1177 #[stable(feature = "rust1", since = "1.0.0")]
1179 pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
1181 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1183 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1186 /// An iterator over substrings of this string slice, separated by
1187 /// characters matched by a pattern.
1189 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1190 /// function or closure that determines if a character matches.
1192 /// [`char`]: prim@char
1193 /// [pattern]: self::pattern
1195 /// # Iterator behavior
1197 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1198 /// allows a reverse search and forward/reverse search yields the same
1199 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1201 /// If the pattern allows a reverse search but its results might differ
1202 /// from a forward search, the [`rsplit`] method can be used.
1204 /// [`rsplit`]: str::rsplit
1208 /// Simple patterns:
1211 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1212 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1214 /// let v: Vec<&str> = "".split('X').collect();
1215 /// assert_eq!(v, [""]);
1217 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1218 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1220 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1221 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1223 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1224 /// assert_eq!(v, ["abc", "def", "ghi"]);
1226 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1227 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1230 /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1233 /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1234 /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1237 /// A more complex pattern, using a closure:
1240 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1241 /// assert_eq!(v, ["abc", "def", "ghi"]);
1244 /// If a string contains multiple contiguous separators, you will end up
1245 /// with empty strings in the output:
1248 /// let x = "||||a||b|c".to_string();
1249 /// let d: Vec<_> = x.split('|').collect();
1251 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1254 /// Contiguous separators are separated by the empty string.
1257 /// let x = "(///)".to_string();
1258 /// let d: Vec<_> = x.split('/').collect();
1260 /// assert_eq!(d, &["(", "", "", ")"]);
1263 /// Separators at the start or end of a string are neighbored
1264 /// by empty strings.
1267 /// let d: Vec<_> = "010".split("0").collect();
1268 /// assert_eq!(d, &["", "1", ""]);
1271 /// When the empty string is used as a separator, it separates
1272 /// every character in the string, along with the beginning
1273 /// and end of the string.
1276 /// let f: Vec<_> = "rust".split("").collect();
1277 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1280 /// Contiguous separators can lead to possibly surprising behavior
1281 /// when whitespace is used as the separator. This code is correct:
1284 /// let x = " a b c".to_string();
1285 /// let d: Vec<_> = x.split(' ').collect();
1287 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1290 /// It does _not_ give you:
1293 /// assert_eq!(d, &["a", "b", "c"]);
1296 /// Use [`split_whitespace`] for this behavior.
1298 /// [`split_whitespace`]: str::split_whitespace
1299 #[stable(feature = "rust1", since = "1.0.0")]
1301 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1302 Split(SplitInternal {
1305 matcher: pat.into_searcher(self),
1306 allow_trailing_empty: true,
1311 /// An iterator over substrings of this string slice, separated by
1312 /// characters matched by a pattern. Differs from the iterator produced by
1313 /// `split` in that `split_inclusive` leaves the matched part as the
1314 /// terminator of the substring.
1316 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1317 /// function or closure that determines if a character matches.
1319 /// [`char`]: prim@char
1320 /// [pattern]: self::pattern
1325 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1326 /// .split_inclusive('\n').collect();
1327 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1330 /// If the last element of the string is matched,
1331 /// that element will be considered the terminator of the preceding substring.
1332 /// That substring will be the last item returned by the iterator.
1335 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1336 /// .split_inclusive('\n').collect();
1337 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1339 #[stable(feature = "split_inclusive", since = "1.51.0")]
1341 pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> {
1342 SplitInclusive(SplitInternal {
1345 matcher: pat.into_searcher(self),
1346 allow_trailing_empty: false,
1351 /// An iterator over substrings of the given string slice, separated by
1352 /// characters matched by a pattern and yielded in reverse order.
1354 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1355 /// function or closure that determines if a character matches.
1357 /// [`char`]: prim@char
1358 /// [pattern]: self::pattern
1360 /// # Iterator behavior
1362 /// The returned iterator requires that the pattern supports a reverse
1363 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1364 /// search yields the same elements.
1366 /// For iterating from the front, the [`split`] method can be used.
1368 /// [`split`]: str::split
1372 /// Simple patterns:
1375 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1376 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1378 /// let v: Vec<&str> = "".rsplit('X').collect();
1379 /// assert_eq!(v, [""]);
1381 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1382 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1384 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1385 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1388 /// A more complex pattern, using a closure:
1391 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1392 /// assert_eq!(v, ["ghi", "def", "abc"]);
1394 #[stable(feature = "rust1", since = "1.0.0")]
1396 pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>
1398 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1400 RSplit(self.split(pat).0)
1403 /// An iterator over substrings of the given string slice, separated by
1404 /// characters matched by a pattern.
1406 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1407 /// function or closure that determines if a character matches.
1409 /// [`char`]: prim@char
1410 /// [pattern]: self::pattern
1412 /// Equivalent to [`split`], except that the trailing substring
1413 /// is skipped if empty.
1415 /// [`split`]: str::split
1417 /// This method can be used for string data that is _terminated_,
1418 /// rather than _separated_ by a pattern.
1420 /// # Iterator behavior
1422 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1423 /// allows a reverse search and forward/reverse search yields the same
1424 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1426 /// If the pattern allows a reverse search but its results might differ
1427 /// from a forward search, the [`rsplit_terminator`] method can be used.
1429 /// [`rsplit_terminator`]: str::rsplit_terminator
1436 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1437 /// assert_eq!(v, ["A", "B"]);
1439 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1440 /// assert_eq!(v, ["A", "", "B", ""]);
1442 /// let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
1443 /// assert_eq!(v, ["A", "B", "C", "D"]);
1445 #[stable(feature = "rust1", since = "1.0.0")]
1447 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1448 SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1451 /// An iterator over substrings of `self`, separated by characters
1452 /// matched by a pattern and yielded in reverse order.
1454 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1455 /// function or closure that determines if a character matches.
1457 /// [`char`]: prim@char
1458 /// [pattern]: self::pattern
1460 /// Equivalent to [`split`], except that the trailing substring is
1461 /// skipped if empty.
1463 /// [`split`]: str::split
1465 /// This method can be used for string data that is _terminated_,
1466 /// rather than _separated_ by a pattern.
1468 /// # Iterator behavior
1470 /// The returned iterator requires that the pattern supports a
1471 /// reverse search, and it will be double ended if a forward/reverse
1472 /// search yields the same elements.
1474 /// For iterating from the front, the [`split_terminator`] method can be
1477 /// [`split_terminator`]: str::split_terminator
1482 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1483 /// assert_eq!(v, ["B", "A"]);
1485 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1486 /// assert_eq!(v, ["", "B", "", "A"]);
1488 /// let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
1489 /// assert_eq!(v, ["D", "C", "B", "A"]);
1491 #[stable(feature = "rust1", since = "1.0.0")]
1493 pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1495 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1497 RSplitTerminator(self.split_terminator(pat).0)
1500 /// An iterator over substrings of the given string slice, separated by a
1501 /// pattern, restricted to returning at most `n` items.
1503 /// If `n` substrings are returned, the last substring (the `n`th substring)
1504 /// will contain the remainder of the string.
1506 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1507 /// function or closure that determines if a character matches.
1509 /// [`char`]: prim@char
1510 /// [pattern]: self::pattern
1512 /// # Iterator behavior
1514 /// The returned iterator will not be double ended, because it is
1515 /// not efficient to support.
1517 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1520 /// [`rsplitn`]: str::rsplitn
1524 /// Simple patterns:
1527 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1528 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1530 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1531 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1533 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1534 /// assert_eq!(v, ["abcXdef"]);
1536 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1537 /// assert_eq!(v, [""]);
1540 /// A more complex pattern, using a closure:
1543 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1544 /// assert_eq!(v, ["abc", "defXghi"]);
1546 #[stable(feature = "rust1", since = "1.0.0")]
1548 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1549 SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1552 /// An iterator over substrings of this string slice, separated by a
1553 /// pattern, starting from the end of the string, restricted to returning
1554 /// at most `n` items.
1556 /// If `n` substrings are returned, the last substring (the `n`th substring)
1557 /// will contain the remainder of the string.
1559 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1560 /// function or closure that determines if a character matches.
1562 /// [`char`]: prim@char
1563 /// [pattern]: self::pattern
1565 /// # Iterator behavior
1567 /// The returned iterator will not be double ended, because it is not
1568 /// efficient to support.
1570 /// For splitting from the front, the [`splitn`] method can be used.
1572 /// [`splitn`]: str::splitn
1576 /// Simple patterns:
1579 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1580 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1582 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1583 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1585 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1586 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1589 /// A more complex pattern, using a closure:
1592 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1593 /// assert_eq!(v, ["ghi", "abc1def"]);
1595 #[stable(feature = "rust1", since = "1.0.0")]
1597 pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1599 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1601 RSplitN(self.splitn(n, pat).0)
1604 /// Splits the string on the first occurrence of the specified delimiter and
1605 /// returns prefix before delimiter and suffix after delimiter.
1610 /// assert_eq!("cfg".split_once('='), None);
1611 /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1612 /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1614 #[stable(feature = "str_split_once", since = "1.52.0")]
1616 pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> {
1617 let (start, end) = delimiter.into_searcher(self).next_match()?;
1618 // SAFETY: `Searcher` is known to return valid indices.
1619 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1622 /// Splits the string on the last occurrence of the specified delimiter and
1623 /// returns prefix before delimiter and suffix after delimiter.
1628 /// assert_eq!("cfg".rsplit_once('='), None);
1629 /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
1630 /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1632 #[stable(feature = "str_split_once", since = "1.52.0")]
1634 pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
1636 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1638 let (start, end) = delimiter.into_searcher(self).next_match_back()?;
1639 // SAFETY: `Searcher` is known to return valid indices.
1640 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1643 /// An iterator over the disjoint matches of a pattern within the given string
1646 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1647 /// function or closure that determines if a character matches.
1649 /// [`char`]: prim@char
1650 /// [pattern]: self::pattern
1652 /// # Iterator behavior
1654 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1655 /// allows a reverse search and forward/reverse search yields the same
1656 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1658 /// If the pattern allows a reverse search but its results might differ
1659 /// from a forward search, the [`rmatches`] method can be used.
1661 /// [`rmatches`]: str::matches
1668 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1669 /// assert_eq!(v, ["abc", "abc", "abc"]);
1671 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1672 /// assert_eq!(v, ["1", "2", "3"]);
1674 #[stable(feature = "str_matches", since = "1.2.0")]
1676 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1677 Matches(MatchesInternal(pat.into_searcher(self)))
1680 /// An iterator over the disjoint matches of a pattern within this string slice,
1681 /// yielded in reverse order.
1683 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1684 /// function or closure that determines if a character matches.
1686 /// [`char`]: prim@char
1687 /// [pattern]: self::pattern
1689 /// # Iterator behavior
1691 /// The returned iterator requires that the pattern supports a reverse
1692 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1693 /// search yields the same elements.
1695 /// For iterating from the front, the [`matches`] method can be used.
1697 /// [`matches`]: str::matches
1704 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1705 /// assert_eq!(v, ["abc", "abc", "abc"]);
1707 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1708 /// assert_eq!(v, ["3", "2", "1"]);
1710 #[stable(feature = "str_matches", since = "1.2.0")]
1712 pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>
1714 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1716 RMatches(self.matches(pat).0)
1719 /// An iterator over the disjoint matches of a pattern within this string
1720 /// slice as well as the index that the match starts at.
1722 /// For matches of `pat` within `self` that overlap, only the indices
1723 /// corresponding to the first match are returned.
1725 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1726 /// function or closure that determines if a character matches.
1728 /// [`char`]: prim@char
1729 /// [pattern]: self::pattern
1731 /// # Iterator behavior
1733 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1734 /// allows a reverse search and forward/reverse search yields the same
1735 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1737 /// If the pattern allows a reverse search but its results might differ
1738 /// from a forward search, the [`rmatch_indices`] method can be used.
1740 /// [`rmatch_indices`]: str::rmatch_indices
1747 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1748 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1750 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1751 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1753 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1754 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1756 #[stable(feature = "str_match_indices", since = "1.5.0")]
1758 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1759 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1762 /// An iterator over the disjoint matches of a pattern within `self`,
1763 /// yielded in reverse order along with the index of the match.
1765 /// For matches of `pat` within `self` that overlap, only the indices
1766 /// corresponding to the last match are returned.
1768 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1769 /// function or closure that determines if a character matches.
1771 /// [`char`]: prim@char
1772 /// [pattern]: self::pattern
1774 /// # Iterator behavior
1776 /// The returned iterator requires that the pattern supports a reverse
1777 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1778 /// search yields the same elements.
1780 /// For iterating from the front, the [`match_indices`] method can be used.
1782 /// [`match_indices`]: str::match_indices
1789 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1790 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1792 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1793 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1795 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1796 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1798 #[stable(feature = "str_match_indices", since = "1.5.0")]
1800 pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>
1802 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1804 RMatchIndices(self.match_indices(pat).0)
1807 /// Returns a string slice with leading and trailing whitespace removed.
1809 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1810 /// Core Property `White_Space`.
1817 /// let s = " Hello\tworld\t";
1819 /// assert_eq!("Hello\tworld", s.trim());
1822 #[must_use = "this returns the trimmed string as a slice, \
1823 without modifying the original"]
1824 #[stable(feature = "rust1", since = "1.0.0")]
1825 pub fn trim(&self) -> &str {
1826 self.trim_matches(|c: char| c.is_whitespace())
1829 /// Returns a string slice with leading whitespace removed.
1831 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1832 /// Core Property `White_Space`.
1834 /// # Text directionality
1836 /// A string is a sequence of bytes. `start` in this context means the first
1837 /// position of that byte string; for a left-to-right language like English or
1838 /// Russian, this will be left side, and for right-to-left languages like
1839 /// Arabic or Hebrew, this will be the right side.
1846 /// let s = " Hello\tworld\t";
1847 /// assert_eq!("Hello\tworld\t", s.trim_start());
1853 /// let s = " English ";
1854 /// assert!(Some('E') == s.trim_start().chars().next());
1856 /// let s = " עברית ";
1857 /// assert!(Some('ע') == s.trim_start().chars().next());
1860 #[must_use = "this returns the trimmed string as a new slice, \
1861 without modifying the original"]
1862 #[stable(feature = "trim_direction", since = "1.30.0")]
1863 pub fn trim_start(&self) -> &str {
1864 self.trim_start_matches(|c: char| c.is_whitespace())
1867 /// Returns a string slice with trailing whitespace removed.
1869 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1870 /// Core Property `White_Space`.
1872 /// # Text directionality
1874 /// A string is a sequence of bytes. `end` in this context means the last
1875 /// position of that byte string; for a left-to-right language like English or
1876 /// Russian, this will be right side, and for right-to-left languages like
1877 /// Arabic or Hebrew, this will be the left side.
1884 /// let s = " Hello\tworld\t";
1885 /// assert_eq!(" Hello\tworld", s.trim_end());
1891 /// let s = " English ";
1892 /// assert!(Some('h') == s.trim_end().chars().rev().next());
1894 /// let s = " עברית ";
1895 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
1898 #[must_use = "this returns the trimmed string as a new slice, \
1899 without modifying the original"]
1900 #[stable(feature = "trim_direction", since = "1.30.0")]
1901 pub fn trim_end(&self) -> &str {
1902 self.trim_end_matches(|c: char| c.is_whitespace())
1905 /// Returns a string slice with leading whitespace removed.
1907 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1908 /// Core Property `White_Space`.
1910 /// # Text directionality
1912 /// A string is a sequence of bytes. 'Left' in this context means the first
1913 /// position of that byte string; for a language like Arabic or Hebrew
1914 /// which are 'right to left' rather than 'left to right', this will be
1915 /// the _right_ side, not the left.
1922 /// let s = " Hello\tworld\t";
1924 /// assert_eq!("Hello\tworld\t", s.trim_left());
1930 /// let s = " English";
1931 /// assert!(Some('E') == s.trim_left().chars().next());
1933 /// let s = " עברית";
1934 /// assert!(Some('ע') == s.trim_left().chars().next());
1936 #[must_use = "this returns the trimmed string as a new slice, \
1937 without modifying the original"]
1939 #[stable(feature = "rust1", since = "1.0.0")]
1942 reason = "superseded by `trim_start`",
1943 suggestion = "trim_start"
1945 pub fn trim_left(&self) -> &str {
1949 /// Returns a string slice with trailing whitespace removed.
1951 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1952 /// Core Property `White_Space`.
1954 /// # Text directionality
1956 /// A string is a sequence of bytes. 'Right' in this context means the last
1957 /// position of that byte string; for a language like Arabic or Hebrew
1958 /// which are 'right to left' rather than 'left to right', this will be
1959 /// the _left_ side, not the right.
1966 /// let s = " Hello\tworld\t";
1968 /// assert_eq!(" Hello\tworld", s.trim_right());
1974 /// let s = "English ";
1975 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1977 /// let s = "עברית ";
1978 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1980 #[must_use = "this returns the trimmed string as a new slice, \
1981 without modifying the original"]
1983 #[stable(feature = "rust1", since = "1.0.0")]
1986 reason = "superseded by `trim_end`",
1987 suggestion = "trim_end"
1989 pub fn trim_right(&self) -> &str {
1993 /// Returns a string slice with all prefixes and suffixes that match a
1994 /// pattern repeatedly removed.
1996 /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
1997 /// or closure that determines if a character matches.
1999 /// [`char`]: prim@char
2000 /// [pattern]: self::pattern
2004 /// Simple patterns:
2007 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
2008 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
2010 /// let x: &[_] = &['1', '2'];
2011 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
2014 /// A more complex pattern, using a closure:
2017 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
2019 #[must_use = "this returns the trimmed string as a new slice, \
2020 without modifying the original"]
2021 #[stable(feature = "rust1", since = "1.0.0")]
2022 pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
2024 P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
2028 let mut matcher = pat.into_searcher(self);
2029 if let Some((a, b)) = matcher.next_reject() {
2031 j = b; // Remember earliest known match, correct it below if
2032 // last match is different
2034 if let Some((_, b)) = matcher.next_reject_back() {
2037 // SAFETY: `Searcher` is known to return valid indices.
2038 unsafe { self.get_unchecked(i..j) }
2041 /// Returns a string slice with all prefixes that match a pattern
2042 /// repeatedly removed.
2044 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2045 /// function or closure that determines if a character matches.
2047 /// [`char`]: prim@char
2048 /// [pattern]: self::pattern
2050 /// # Text directionality
2052 /// A string is a sequence of bytes. `start` in this context means the first
2053 /// position of that byte string; for a left-to-right language like English or
2054 /// Russian, this will be left side, and for right-to-left languages like
2055 /// Arabic or Hebrew, this will be the right side.
2062 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
2063 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
2065 /// let x: &[_] = &['1', '2'];
2066 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
2068 #[must_use = "this returns the trimmed string as a new slice, \
2069 without modifying the original"]
2070 #[stable(feature = "trim_direction", since = "1.30.0")]
2071 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2072 let mut i = self.len();
2073 let mut matcher = pat.into_searcher(self);
2074 if let Some((a, _)) = matcher.next_reject() {
2077 // SAFETY: `Searcher` is known to return valid indices.
2078 unsafe { self.get_unchecked(i..self.len()) }
2081 /// Returns a string slice with the prefix removed.
2083 /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped
2084 /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once.
2086 /// If the string does not start with `prefix`, returns `None`.
2088 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2089 /// function or closure that determines if a character matches.
2091 /// [`char`]: prim@char
2092 /// [pattern]: self::pattern
2097 /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2098 /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2099 /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2101 #[must_use = "this returns the remaining substring as a new slice, \
2102 without modifying the original"]
2103 #[stable(feature = "str_strip", since = "1.45.0")]
2104 pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> {
2105 prefix.strip_prefix_of(self)
2108 /// Returns a string slice with the suffix removed.
2110 /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2111 /// wrapped in `Some`. Unlike `trim_end_matches`, this method removes the suffix exactly once.
2113 /// If the string does not end with `suffix`, returns `None`.
2115 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2116 /// function or closure that determines if a character matches.
2118 /// [`char`]: prim@char
2119 /// [pattern]: self::pattern
2124 /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2125 /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2126 /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2128 #[must_use = "this returns the remaining substring as a new slice, \
2129 without modifying the original"]
2130 #[stable(feature = "str_strip", since = "1.45.0")]
2131 pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
2134 <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
2136 suffix.strip_suffix_of(self)
2139 /// Returns a string slice with all suffixes that match a pattern
2140 /// repeatedly removed.
2142 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2143 /// function or closure that determines if a character matches.
2145 /// [`char`]: prim@char
2146 /// [pattern]: self::pattern
2148 /// # Text directionality
2150 /// A string is a sequence of bytes. `end` in this context means the last
2151 /// position of that byte string; for a left-to-right language like English or
2152 /// Russian, this will be right side, and for right-to-left languages like
2153 /// Arabic or Hebrew, this will be the left side.
2157 /// Simple patterns:
2160 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2161 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2163 /// let x: &[_] = &['1', '2'];
2164 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2167 /// A more complex pattern, using a closure:
2170 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2172 #[must_use = "this returns the trimmed string as a new slice, \
2173 without modifying the original"]
2174 #[stable(feature = "trim_direction", since = "1.30.0")]
2175 pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
2177 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2180 let mut matcher = pat.into_searcher(self);
2181 if let Some((_, b)) = matcher.next_reject_back() {
2184 // SAFETY: `Searcher` is known to return valid indices.
2185 unsafe { self.get_unchecked(0..j) }
2188 /// Returns a string slice with all prefixes that match a pattern
2189 /// repeatedly removed.
2191 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2192 /// function or closure that determines if a character matches.
2194 /// [`char`]: prim@char
2195 /// [pattern]: self::pattern
2197 /// # Text directionality
2199 /// A string is a sequence of bytes. 'Left' in this context means the first
2200 /// position of that byte string; for a language like Arabic or Hebrew
2201 /// which are 'right to left' rather than 'left to right', this will be
2202 /// the _right_ side, not the left.
2209 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2210 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2212 /// let x: &[_] = &['1', '2'];
2213 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2215 #[stable(feature = "rust1", since = "1.0.0")]
2218 reason = "superseded by `trim_start_matches`",
2219 suggestion = "trim_start_matches"
2221 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2222 self.trim_start_matches(pat)
2225 /// Returns a string slice with all suffixes that match a pattern
2226 /// repeatedly removed.
2228 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2229 /// function or closure that determines if a character matches.
2231 /// [`char`]: prim@char
2232 /// [pattern]: self::pattern
2234 /// # Text directionality
2236 /// A string is a sequence of bytes. 'Right' in this context means the last
2237 /// position of that byte string; for a language like Arabic or Hebrew
2238 /// which are 'right to left' rather than 'left to right', this will be
2239 /// the _left_ side, not the right.
2243 /// Simple patterns:
2246 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2247 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2249 /// let x: &[_] = &['1', '2'];
2250 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2253 /// A more complex pattern, using a closure:
2256 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2258 #[stable(feature = "rust1", since = "1.0.0")]
2261 reason = "superseded by `trim_end_matches`",
2262 suggestion = "trim_end_matches"
2264 pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
2266 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2268 self.trim_end_matches(pat)
2271 /// Parses this string slice into another type.
2273 /// Because `parse` is so general, it can cause problems with type
2274 /// inference. As such, `parse` is one of the few times you'll see
2275 /// the syntax affectionately known as the 'turbofish': `::<>`. This
2276 /// helps the inference algorithm understand specifically which type
2277 /// you're trying to parse into.
2279 /// `parse` can parse into any type that implements the [`FromStr`] trait.
2284 /// Will return [`Err`] if it's not possible to parse this string slice into
2285 /// the desired type.
2287 /// [`Err`]: FromStr::Err
2294 /// let four: u32 = "4".parse().unwrap();
2296 /// assert_eq!(4, four);
2299 /// Using the 'turbofish' instead of annotating `four`:
2302 /// let four = "4".parse::<u32>();
2304 /// assert_eq!(Ok(4), four);
2307 /// Failing to parse:
2310 /// let nope = "j".parse::<u32>();
2312 /// assert!(nope.is_err());
2315 #[stable(feature = "rust1", since = "1.0.0")]
2316 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2317 FromStr::from_str(self)
2320 /// Checks if all characters in this string are within the ASCII range.
2325 /// let ascii = "hello!\n";
2326 /// let non_ascii = "Grüße, Jürgen ❤";
2328 /// assert!(ascii.is_ascii());
2329 /// assert!(!non_ascii.is_ascii());
2331 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2334 pub fn is_ascii(&self) -> bool {
2335 // We can treat each byte as character here: all multibyte characters
2336 // start with a byte that is not in the ascii range, so we will stop
2338 self.as_bytes().is_ascii()
2341 /// Checks that two strings are an ASCII case-insensitive match.
2343 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2344 /// but without allocating and copying temporaries.
2349 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2350 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2351 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2353 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2356 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2357 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2360 /// Converts this string to its ASCII upper case equivalent in-place.
2362 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2363 /// but non-ASCII letters are unchanged.
2365 /// To return a new uppercased value without modifying the existing one, use
2366 /// [`to_ascii_uppercase()`].
2368 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2373 /// let mut s = String::from("Grüße, Jürgen ❤");
2375 /// s.make_ascii_uppercase();
2377 /// assert_eq!("GRüßE, JüRGEN ❤", s);
2379 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2381 pub fn make_ascii_uppercase(&mut self) {
2382 // SAFETY: safe because we transmute two types with the same layout.
2383 let me = unsafe { self.as_bytes_mut() };
2384 me.make_ascii_uppercase()
2387 /// Converts this string to its ASCII lower case equivalent in-place.
2389 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2390 /// but non-ASCII letters are unchanged.
2392 /// To return a new lowercased value without modifying the existing one, use
2393 /// [`to_ascii_lowercase()`].
2395 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2400 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2402 /// s.make_ascii_lowercase();
2404 /// assert_eq!("grÜße, jÜrgen ❤", s);
2406 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2408 pub fn make_ascii_lowercase(&mut self) {
2409 // SAFETY: safe because we transmute two types with the same layout.
2410 let me = unsafe { self.as_bytes_mut() };
2411 me.make_ascii_lowercase()
2414 /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
2416 /// Note: only extended grapheme codepoints that begin the string will be
2424 /// for c in "❤\n!".escape_debug() {
2425 /// print!("{}", c);
2430 /// Using `println!` directly:
2433 /// println!("{}", "❤\n!".escape_debug());
2437 /// Both are equivalent to:
2440 /// println!("❤\\n!");
2443 /// Using `to_string`:
2446 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
2448 #[must_use = "this returns the escaped string as an iterator, \
2449 without modifying the original"]
2450 #[stable(feature = "str_escape", since = "1.34.0")]
2451 pub fn escape_debug(&self) -> EscapeDebug<'_> {
2452 let mut chars = self.chars();
2456 .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL))
2459 .chain(chars.flat_map(CharEscapeDebugContinue)),
2463 /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
2470 /// for c in "❤\n!".escape_default() {
2471 /// print!("{}", c);
2476 /// Using `println!` directly:
2479 /// println!("{}", "❤\n!".escape_default());
2483 /// Both are equivalent to:
2486 /// println!("\\u{{2764}}\\n!");
2489 /// Using `to_string`:
2492 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
2494 #[must_use = "this returns the escaped string as an iterator, \
2495 without modifying the original"]
2496 #[stable(feature = "str_escape", since = "1.34.0")]
2497 pub fn escape_default(&self) -> EscapeDefault<'_> {
2498 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
2501 /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
2508 /// for c in "❤\n!".escape_unicode() {
2509 /// print!("{}", c);
2514 /// Using `println!` directly:
2517 /// println!("{}", "❤\n!".escape_unicode());
2521 /// Both are equivalent to:
2524 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
2527 /// Using `to_string`:
2530 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
2532 #[must_use = "this returns the escaped string as an iterator, \
2533 without modifying the original"]
2534 #[stable(feature = "str_escape", since = "1.34.0")]
2535 pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
2536 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
2540 #[stable(feature = "rust1", since = "1.0.0")]
2541 impl AsRef<[u8]> for str {
2543 fn as_ref(&self) -> &[u8] {
2548 #[stable(feature = "rust1", since = "1.0.0")]
2549 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
2550 impl const Default for &str {
2551 /// Creates an empty str
2553 fn default() -> Self {
2558 #[stable(feature = "default_mut_str", since = "1.28.0")]
2559 impl Default for &mut str {
2560 /// Creates an empty mutable str
2562 fn default() -> Self {
2563 // SAFETY: The empty string is valid UTF-8.
2564 unsafe { from_utf8_unchecked_mut(&mut []) }
2569 /// A nameable, cloneable fn type
2571 struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
2573 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
2578 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
2579 c.escape_debug_ext(EscapeDebugExtArgs {
2580 escape_grapheme_extended: false,
2581 escape_single_quote: true,
2582 escape_double_quote: true
2587 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
2591 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
2596 struct IsWhitespace impl Fn = |c: char| -> bool {
2601 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
2602 byte.is_ascii_whitespace()
2606 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
2611 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
2616 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
2618 unsafe { from_utf8_unchecked(bytes) }