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};
26 #[unstable(feature = "utf8_chunks", issue = "99543")]
27 pub use lossy::{Utf8Chunk, Utf8Chunks};
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 #[rustc_allow_const_fn_unstable(const_eval_select)]
83 const fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
84 // SAFETY: panics for both branches
86 crate::intrinsics::const_eval_select(
95 const fn slice_error_fail_ct(_: &str, _: usize, _: usize) -> ! {
96 panic!("failed to slice string");
100 fn slice_error_fail_rt(s: &str, begin: usize, end: usize) -> ! {
101 const MAX_DISPLAY_LENGTH: usize = 256;
102 let trunc_len = s.floor_char_boundary(MAX_DISPLAY_LENGTH);
103 let s_trunc = &s[..trunc_len];
104 let ellipsis = if trunc_len < s.len() { "[...]" } else { "" };
107 if begin > s.len() || end > s.len() {
108 let oob_index = if begin > s.len() { begin } else { end };
109 panic!("byte index {oob_index} is out of bounds of `{s_trunc}`{ellipsis}");
115 "begin <= end ({} <= {}) when slicing `{}`{}",
122 // 3. character boundary
123 let index = if !s.is_char_boundary(begin) { begin } else { end };
124 // find the character
125 let char_start = s.floor_char_boundary(index);
126 // `char_start` must be less than len and a char boundary
127 let ch = s[char_start..].chars().next().unwrap();
128 let char_range = char_start..char_start + ch.len_utf8();
130 "byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
131 index, ch, char_range, s_trunc, ellipsis
137 /// Returns the length of `self`.
139 /// This length is in bytes, not [`char`]s or graphemes. In other words,
140 /// it might not be what a human considers the length of the string.
142 /// [`char`]: prim@char
149 /// let len = "foo".len();
150 /// assert_eq!(3, len);
152 /// assert_eq!("ƒoo".len(), 4); // fancy f!
153 /// assert_eq!("ƒoo".chars().count(), 3);
155 #[stable(feature = "rust1", since = "1.0.0")]
156 #[rustc_const_stable(feature = "const_str_len", since = "1.39.0")]
159 pub const fn len(&self) -> usize {
160 self.as_bytes().len()
163 /// Returns `true` if `self` has a length of zero bytes.
171 /// assert!(s.is_empty());
173 /// let s = "not empty";
174 /// assert!(!s.is_empty());
176 #[stable(feature = "rust1", since = "1.0.0")]
177 #[rustc_const_stable(feature = "const_str_is_empty", since = "1.39.0")]
180 pub const fn is_empty(&self) -> bool {
184 /// Checks that `index`-th byte is the first byte in a UTF-8 code point
185 /// sequence or the end of the string.
187 /// The start and end of the string (when `index == self.len()`) are
188 /// considered to be boundaries.
190 /// Returns `false` if `index` is greater than `self.len()`.
195 /// let s = "Löwe 老虎 Léopard";
196 /// assert!(s.is_char_boundary(0));
198 /// assert!(s.is_char_boundary(6));
199 /// assert!(s.is_char_boundary(s.len()));
201 /// // second byte of `ö`
202 /// assert!(!s.is_char_boundary(2));
204 /// // third byte of `老`
205 /// assert!(!s.is_char_boundary(8));
208 #[stable(feature = "is_char_boundary", since = "1.9.0")]
209 #[rustc_const_unstable(feature = "const_is_char_boundary", issue = "none")]
211 pub const fn is_char_boundary(&self, index: usize) -> bool {
213 // Test for 0 explicitly so that it can optimize out the check
214 // easily and skip reading string data for that case.
215 // Note that optimizing `self.get(..index)` relies on this.
220 match self.as_bytes().get(index) {
221 // For `None` we have two options:
223 // - index == self.len()
224 // Empty strings are valid, so return true
225 // - index > self.len()
226 // In this case return false
228 // The check is placed exactly here, because it improves generated
229 // code on higher opt-levels. See PR #84751 for more details.
230 None => index == self.len(),
232 Some(&b) => b.is_utf8_char_boundary(),
236 /// Finds the closest `x` not exceeding `index` where `is_char_boundary(x)` is `true`.
238 /// This method can help you truncate a string so that it's still valid UTF-8, but doesn't
239 /// exceed a given number of bytes. Note that this is done purely at the character level
240 /// and can still visually split graphemes, even though the underlying characters aren't
241 /// split. For example, the emoji 🧑🔬 (scientist) could be split so that the string only
242 /// includes 🧑 (person) instead.
247 /// #![feature(round_char_boundary)]
248 /// let s = "❤️🧡💛💚💙💜";
249 /// assert_eq!(s.len(), 26);
250 /// assert!(!s.is_char_boundary(13));
252 /// let closest = s.floor_char_boundary(13);
253 /// assert_eq!(closest, 10);
254 /// assert_eq!(&s[..closest], "❤️🧡");
256 #[unstable(feature = "round_char_boundary", issue = "93743")]
258 pub fn floor_char_boundary(&self, index: usize) -> usize {
259 if index >= self.len() {
262 let lower_bound = index.saturating_sub(3);
263 let new_index = self.as_bytes()[lower_bound..=index]
265 .rposition(|b| b.is_utf8_char_boundary());
267 // SAFETY: we know that the character boundary will be within four bytes
268 unsafe { lower_bound + new_index.unwrap_unchecked() }
272 /// Finds the closest `x` not below `index` where `is_char_boundary(x)` is `true`.
274 /// This method is the natural complement to [`floor_char_boundary`]. See that method
275 /// for more details.
277 /// [`floor_char_boundary`]: str::floor_char_boundary
281 /// Panics if `index > self.len()`.
286 /// #![feature(round_char_boundary)]
287 /// let s = "❤️🧡💛💚💙💜";
288 /// assert_eq!(s.len(), 26);
289 /// assert!(!s.is_char_boundary(13));
291 /// let closest = s.ceil_char_boundary(13);
292 /// assert_eq!(closest, 14);
293 /// assert_eq!(&s[..closest], "❤️🧡💛");
295 #[unstable(feature = "round_char_boundary", issue = "93743")]
297 pub fn ceil_char_boundary(&self, index: usize) -> usize {
298 if index > self.len() {
299 slice_error_fail(self, index, index)
301 let upper_bound = Ord::min(index + 4, self.len());
302 self.as_bytes()[index..upper_bound]
304 .position(|b| b.is_utf8_char_boundary())
305 .map_or(upper_bound, |pos| pos + index)
309 /// Converts a string slice to a byte slice. To convert the byte slice back
310 /// into a string slice, use the [`from_utf8`] function.
317 /// let bytes = "bors".as_bytes();
318 /// assert_eq!(b"bors", bytes);
320 #[stable(feature = "rust1", since = "1.0.0")]
321 #[rustc_const_stable(feature = "str_as_bytes", since = "1.39.0")]
324 #[allow(unused_attributes)]
325 pub const fn as_bytes(&self) -> &[u8] {
326 // SAFETY: const sound because we transmute two types with the same layout
327 unsafe { mem::transmute(self) }
330 /// Converts a mutable string slice to a mutable byte slice.
334 /// The caller must ensure that the content of the slice is valid UTF-8
335 /// before the borrow ends and the underlying `str` is used.
337 /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
344 /// let mut s = String::from("Hello");
345 /// let bytes = unsafe { s.as_bytes_mut() };
347 /// assert_eq!(b"Hello", bytes);
353 /// let mut s = String::from("🗻∈🌏");
356 /// let bytes = s.as_bytes_mut();
364 /// assert_eq!("🍔∈🌏", s);
366 #[stable(feature = "str_mut_extras", since = "1.20.0")]
369 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
370 // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
371 // has the same layout as `&[u8]` (only libstd can make this guarantee).
372 // The pointer dereference is safe since it comes from a mutable reference which
373 // is guaranteed to be valid for writes.
374 unsafe { &mut *(self as *mut str as *mut [u8]) }
377 /// Converts a string slice to a raw pointer.
379 /// As string slices are a slice of bytes, the raw pointer points to a
380 /// [`u8`]. This pointer will be pointing to the first byte of the string
383 /// The caller must ensure that the returned pointer is never written to.
384 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
386 /// [`as_mut_ptr`]: str::as_mut_ptr
394 /// let ptr = s.as_ptr();
396 #[stable(feature = "rust1", since = "1.0.0")]
397 #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
400 pub const fn as_ptr(&self) -> *const u8 {
401 self as *const str as *const u8
404 /// Converts a mutable string slice to a raw pointer.
406 /// As string slices are a slice of bytes, the raw pointer points to a
407 /// [`u8`]. This pointer will be pointing to the first byte of the string
410 /// It is your responsibility to make sure that the string slice only gets
411 /// modified in a way that it remains valid UTF-8.
412 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
415 pub fn as_mut_ptr(&mut self) -> *mut u8 {
416 self as *mut str as *mut u8
419 /// Returns a subslice of `str`.
421 /// This is the non-panicking alternative to indexing the `str`. Returns
422 /// [`None`] whenever equivalent indexing operation would panic.
427 /// let v = String::from("🗻∈🌏");
429 /// assert_eq!(Some("🗻"), v.get(0..4));
431 /// // indices not on UTF-8 sequence boundaries
432 /// assert!(v.get(1..).is_none());
433 /// assert!(v.get(..8).is_none());
436 /// assert!(v.get(..42).is_none());
438 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
439 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
441 pub const fn get<I: ~const SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
445 /// Returns a mutable subslice of `str`.
447 /// This is the non-panicking alternative to indexing the `str`. Returns
448 /// [`None`] whenever equivalent indexing operation would panic.
453 /// let mut v = String::from("hello");
454 /// // correct length
455 /// assert!(v.get_mut(0..5).is_some());
457 /// assert!(v.get_mut(..42).is_none());
458 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
460 /// assert_eq!("hello", v);
462 /// let s = v.get_mut(0..2);
463 /// let s = s.map(|s| {
464 /// s.make_ascii_uppercase();
467 /// assert_eq!(Some("HE"), s);
469 /// assert_eq!("HEllo", v);
471 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
472 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
474 pub const fn get_mut<I: ~const SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
478 /// Returns an unchecked subslice of `str`.
480 /// This is the unchecked alternative to indexing the `str`.
484 /// Callers of this function are responsible that these preconditions are
487 /// * The starting index must not exceed the ending index;
488 /// * Indexes must be within bounds of the original slice;
489 /// * Indexes must lie on UTF-8 sequence boundaries.
491 /// Failing that, the returned string slice may reference invalid memory or
492 /// violate the invariants communicated by the `str` type.
499 /// assert_eq!("🗻", v.get_unchecked(0..4));
500 /// assert_eq!("∈", v.get_unchecked(4..7));
501 /// assert_eq!("🌏", v.get_unchecked(7..11));
504 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
505 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
507 pub const unsafe fn get_unchecked<I: ~const SliceIndex<str>>(&self, i: I) -> &I::Output {
508 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
509 // the slice is dereferenceable because `self` is a safe reference.
510 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
511 unsafe { &*i.get_unchecked(self) }
514 /// Returns a mutable, unchecked subslice of `str`.
516 /// This is the unchecked alternative to indexing the `str`.
520 /// Callers of this function are responsible that these preconditions are
523 /// * The starting index must not exceed the ending index;
524 /// * Indexes must be within bounds of the original slice;
525 /// * Indexes must lie on UTF-8 sequence boundaries.
527 /// Failing that, the returned string slice may reference invalid memory or
528 /// violate the invariants communicated by the `str` type.
533 /// let mut v = String::from("🗻∈🌏");
535 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
536 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
537 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
540 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
541 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
543 pub const unsafe fn get_unchecked_mut<I: ~const SliceIndex<str>>(
546 ) -> &mut I::Output {
547 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
548 // the slice is dereferenceable because `self` is a safe reference.
549 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
550 unsafe { &mut *i.get_unchecked_mut(self) }
553 /// Creates a string slice from another string slice, bypassing safety
556 /// This is generally not recommended, use with caution! For a safe
557 /// alternative see [`str`] and [`Index`].
559 /// [`Index`]: crate::ops::Index
561 /// This new slice goes from `begin` to `end`, including `begin` but
564 /// To get a mutable string slice instead, see the
565 /// [`slice_mut_unchecked`] method.
567 /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
571 /// Callers of this function are responsible that three preconditions are
574 /// * `begin` must not exceed `end`.
575 /// * `begin` and `end` must be byte positions within the string slice.
576 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
583 /// let s = "Löwe 老虎 Léopard";
586 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
589 /// let s = "Hello, world!";
592 /// assert_eq!("world", s.slice_unchecked(7, 12));
595 #[stable(feature = "rust1", since = "1.0.0")]
596 #[deprecated(since = "1.29.0", note = "use `get_unchecked(begin..end)` instead")]
599 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
600 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
601 // the slice is dereferenceable because `self` is a safe reference.
602 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
603 unsafe { &*(begin..end).get_unchecked(self) }
606 /// Creates a string slice from another string slice, bypassing safety
608 /// This is generally not recommended, use with caution! For a safe
609 /// alternative see [`str`] and [`IndexMut`].
611 /// [`IndexMut`]: crate::ops::IndexMut
613 /// This new slice goes from `begin` to `end`, including `begin` but
616 /// To get an immutable string slice instead, see the
617 /// [`slice_unchecked`] method.
619 /// [`slice_unchecked`]: str::slice_unchecked
623 /// Callers of this function are responsible that three preconditions are
626 /// * `begin` must not exceed `end`.
627 /// * `begin` and `end` must be byte positions within the string slice.
628 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
629 #[stable(feature = "str_slice_mut", since = "1.5.0")]
630 #[deprecated(since = "1.29.0", note = "use `get_unchecked_mut(begin..end)` instead")]
632 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
633 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
634 // the slice is dereferenceable because `self` is a safe reference.
635 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
636 unsafe { &mut *(begin..end).get_unchecked_mut(self) }
639 /// Divide one string slice into two at an index.
641 /// The argument, `mid`, should be a byte offset from the start of the
642 /// string. It must also be on the boundary of a UTF-8 code point.
644 /// The two slices returned go from the start of the string slice to `mid`,
645 /// and from `mid` to the end of the string slice.
647 /// To get mutable string slices instead, see the [`split_at_mut`]
650 /// [`split_at_mut`]: str::split_at_mut
654 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
655 /// past the end of the last code point of the string slice.
662 /// let s = "Per Martin-Löf";
664 /// let (first, last) = s.split_at(3);
666 /// assert_eq!("Per", first);
667 /// assert_eq!(" Martin-Löf", last);
671 #[stable(feature = "str_split_at", since = "1.4.0")]
672 pub fn split_at(&self, mid: usize) -> (&str, &str) {
673 // is_char_boundary checks that the index is in [0, .len()]
674 if self.is_char_boundary(mid) {
675 // SAFETY: just checked that `mid` is on a char boundary.
676 unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) }
678 slice_error_fail(self, 0, mid)
682 /// Divide one mutable string slice into two at an index.
684 /// The argument, `mid`, should be a byte offset from the start of the
685 /// string. It must also be on the boundary of a UTF-8 code point.
687 /// The two slices returned go from the start of the string slice to `mid`,
688 /// and from `mid` to the end of the string slice.
690 /// To get immutable string slices instead, see the [`split_at`] method.
692 /// [`split_at`]: str::split_at
696 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
697 /// past the end of the last code point of the string slice.
704 /// let mut s = "Per Martin-Löf".to_string();
706 /// let (first, last) = s.split_at_mut(3);
707 /// first.make_ascii_uppercase();
708 /// assert_eq!("PER", first);
709 /// assert_eq!(" Martin-Löf", last);
711 /// assert_eq!("PER Martin-Löf", s);
715 #[stable(feature = "str_split_at", since = "1.4.0")]
716 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
717 // is_char_boundary checks that the index is in [0, .len()]
718 if self.is_char_boundary(mid) {
719 let len = self.len();
720 let ptr = self.as_mut_ptr();
721 // SAFETY: just checked that `mid` is on a char boundary.
724 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
725 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
729 slice_error_fail(self, 0, mid)
733 /// Returns an iterator over the [`char`]s of a string slice.
735 /// As a string slice consists of valid UTF-8, we can iterate through a
736 /// string slice by [`char`]. This method returns such an iterator.
738 /// It's important to remember that [`char`] represents a Unicode Scalar
739 /// Value, and might not match your idea of what a 'character' is. Iteration
740 /// over grapheme clusters may be what you actually want. This functionality
741 /// is not provided by Rust's standard library, check crates.io instead.
748 /// let word = "goodbye";
750 /// let count = word.chars().count();
751 /// assert_eq!(7, count);
753 /// let mut chars = word.chars();
755 /// assert_eq!(Some('g'), chars.next());
756 /// assert_eq!(Some('o'), chars.next());
757 /// assert_eq!(Some('o'), chars.next());
758 /// assert_eq!(Some('d'), chars.next());
759 /// assert_eq!(Some('b'), chars.next());
760 /// assert_eq!(Some('y'), chars.next());
761 /// assert_eq!(Some('e'), chars.next());
763 /// assert_eq!(None, chars.next());
766 /// Remember, [`char`]s might not match your intuition about characters:
768 /// [`char`]: prim@char
773 /// let mut chars = y.chars();
775 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
776 /// assert_eq!(Some('\u{0306}'), chars.next());
778 /// assert_eq!(None, chars.next());
780 #[stable(feature = "rust1", since = "1.0.0")]
782 pub fn chars(&self) -> Chars<'_> {
783 Chars { iter: self.as_bytes().iter() }
786 /// Returns an iterator over the [`char`]s of a string slice, and their
789 /// As a string slice consists of valid UTF-8, we can iterate through a
790 /// string slice by [`char`]. This method returns an iterator of both
791 /// these [`char`]s, as well as their byte positions.
793 /// The iterator yields tuples. The position is first, the [`char`] is
801 /// let word = "goodbye";
803 /// let count = word.char_indices().count();
804 /// assert_eq!(7, count);
806 /// let mut char_indices = word.char_indices();
808 /// assert_eq!(Some((0, 'g')), char_indices.next());
809 /// assert_eq!(Some((1, 'o')), char_indices.next());
810 /// assert_eq!(Some((2, 'o')), char_indices.next());
811 /// assert_eq!(Some((3, 'd')), char_indices.next());
812 /// assert_eq!(Some((4, 'b')), char_indices.next());
813 /// assert_eq!(Some((5, 'y')), char_indices.next());
814 /// assert_eq!(Some((6, 'e')), char_indices.next());
816 /// assert_eq!(None, char_indices.next());
819 /// Remember, [`char`]s might not match your intuition about characters:
821 /// [`char`]: prim@char
824 /// let yes = "y̆es";
826 /// let mut char_indices = yes.char_indices();
828 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
829 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
831 /// // note the 3 here - the last character took up two bytes
832 /// assert_eq!(Some((3, 'e')), char_indices.next());
833 /// assert_eq!(Some((4, 's')), char_indices.next());
835 /// assert_eq!(None, char_indices.next());
837 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn char_indices(&self) -> CharIndices<'_> {
840 CharIndices { front_offset: 0, iter: self.chars() }
843 /// An iterator over the bytes of a string slice.
845 /// As a string slice consists of a sequence of bytes, we can iterate
846 /// through a string slice by byte. This method returns such an iterator.
853 /// let mut bytes = "bors".bytes();
855 /// assert_eq!(Some(b'b'), bytes.next());
856 /// assert_eq!(Some(b'o'), bytes.next());
857 /// assert_eq!(Some(b'r'), bytes.next());
858 /// assert_eq!(Some(b's'), bytes.next());
860 /// assert_eq!(None, bytes.next());
862 #[stable(feature = "rust1", since = "1.0.0")]
864 pub fn bytes(&self) -> Bytes<'_> {
865 Bytes(self.as_bytes().iter().copied())
868 /// Splits a string slice by whitespace.
870 /// The iterator returned will return string slices that are sub-slices of
871 /// the original string slice, separated by any amount of whitespace.
873 /// 'Whitespace' is defined according to the terms of the Unicode Derived
874 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
875 /// instead, use [`split_ascii_whitespace`].
877 /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
884 /// let mut iter = "A few words".split_whitespace();
886 /// assert_eq!(Some("A"), iter.next());
887 /// assert_eq!(Some("few"), iter.next());
888 /// assert_eq!(Some("words"), iter.next());
890 /// assert_eq!(None, iter.next());
893 /// All kinds of whitespace are considered:
896 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
897 /// assert_eq!(Some("Mary"), iter.next());
898 /// assert_eq!(Some("had"), iter.next());
899 /// assert_eq!(Some("a"), iter.next());
900 /// assert_eq!(Some("little"), iter.next());
901 /// assert_eq!(Some("lamb"), iter.next());
903 /// assert_eq!(None, iter.next());
905 #[must_use = "this returns the split string as an iterator, \
906 without modifying the original"]
907 #[stable(feature = "split_whitespace", since = "1.1.0")]
908 #[cfg_attr(not(test), rustc_diagnostic_item = "str_split_whitespace")]
910 pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
911 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
914 /// Splits a string slice by ASCII whitespace.
916 /// The iterator returned will return string slices that are sub-slices of
917 /// the original string slice, separated by any amount of ASCII whitespace.
919 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
921 /// [`split_whitespace`]: str::split_whitespace
928 /// let mut iter = "A few words".split_ascii_whitespace();
930 /// assert_eq!(Some("A"), iter.next());
931 /// assert_eq!(Some("few"), iter.next());
932 /// assert_eq!(Some("words"), iter.next());
934 /// assert_eq!(None, iter.next());
937 /// All kinds of ASCII whitespace are considered:
940 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
941 /// assert_eq!(Some("Mary"), iter.next());
942 /// assert_eq!(Some("had"), iter.next());
943 /// assert_eq!(Some("a"), iter.next());
944 /// assert_eq!(Some("little"), iter.next());
945 /// assert_eq!(Some("lamb"), iter.next());
947 /// assert_eq!(None, iter.next());
949 #[must_use = "this returns the split string as an iterator, \
950 without modifying the original"]
951 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
953 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
955 self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
956 SplitAsciiWhitespace { inner }
959 /// An iterator over the lines of a string, as string slices.
961 /// Lines are ended with either a newline (`\n`) or a carriage return with
962 /// a line feed (`\r\n`).
964 /// The final line ending is optional. A string that ends with a final line
965 /// ending will return the same lines as an otherwise identical string
966 /// without a final line ending.
973 /// let text = "foo\r\nbar\n\nbaz\n";
974 /// let mut lines = text.lines();
976 /// assert_eq!(Some("foo"), lines.next());
977 /// assert_eq!(Some("bar"), lines.next());
978 /// assert_eq!(Some(""), lines.next());
979 /// assert_eq!(Some("baz"), lines.next());
981 /// assert_eq!(None, lines.next());
984 /// The final line ending isn't required:
987 /// let text = "foo\nbar\n\r\nbaz";
988 /// let mut lines = text.lines();
990 /// assert_eq!(Some("foo"), lines.next());
991 /// assert_eq!(Some("bar"), lines.next());
992 /// assert_eq!(Some(""), lines.next());
993 /// assert_eq!(Some("baz"), lines.next());
995 /// assert_eq!(None, lines.next());
997 #[stable(feature = "rust1", since = "1.0.0")]
999 pub fn lines(&self) -> Lines<'_> {
1000 Lines(self.split_terminator('\n').map(LinesAnyMap))
1003 /// An iterator over the lines of a string.
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 #[deprecated(since = "1.4.0", note = "use lines() instead now")]
1007 #[allow(deprecated)]
1008 pub fn lines_any(&self) -> LinesAny<'_> {
1009 LinesAny(self.lines())
1012 /// Returns an iterator of `u16` over the string encoded as UTF-16.
1019 /// let text = "Zażółć gęślą jaźń";
1021 /// let utf8_len = text.len();
1022 /// let utf16_len = text.encode_utf16().count();
1024 /// assert!(utf16_len <= utf8_len);
1026 #[must_use = "this returns the encoded string as an iterator, \
1027 without modifying the original"]
1028 #[stable(feature = "encode_utf16", since = "1.8.0")]
1029 pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
1030 EncodeUtf16 { chars: self.chars(), extra: 0 }
1033 /// Returns `true` if the given pattern matches a sub-slice of
1034 /// this string slice.
1036 /// Returns `false` if it does not.
1038 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1039 /// function or closure that determines if a character matches.
1041 /// [`char`]: prim@char
1042 /// [pattern]: self::pattern
1049 /// let bananas = "bananas";
1051 /// assert!(bananas.contains("nana"));
1052 /// assert!(!bananas.contains("apples"));
1054 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1057 pat.is_contained_in(self)
1060 /// Returns `true` if the given pattern matches a prefix 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.starts_with("bana"));
1079 /// assert!(!bananas.starts_with("nana"));
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1083 pat.is_prefix_of(self)
1086 /// Returns `true` if the given pattern matches a suffix of this
1089 /// Returns `false` if it does not.
1091 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1092 /// function or closure that determines if a character matches.
1094 /// [`char`]: prim@char
1095 /// [pattern]: self::pattern
1102 /// let bananas = "bananas";
1104 /// assert!(bananas.ends_with("anas"));
1105 /// assert!(!bananas.ends_with("nana"));
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
1110 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1112 pat.is_suffix_of(self)
1115 /// Returns the byte index of the first character of this string slice that
1116 /// matches the pattern.
1118 /// Returns [`None`] if the pattern doesn't match.
1120 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1121 /// function or closure that determines if a character matches.
1123 /// [`char`]: prim@char
1124 /// [pattern]: self::pattern
1128 /// Simple patterns:
1131 /// let s = "Löwe 老虎 Léopard Gepardi";
1133 /// assert_eq!(s.find('L'), Some(0));
1134 /// assert_eq!(s.find('é'), Some(14));
1135 /// assert_eq!(s.find("pard"), Some(17));
1138 /// More complex patterns using point-free style and closures:
1141 /// let s = "Löwe 老虎 Léopard";
1143 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1144 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1145 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1146 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1149 /// Not finding the pattern:
1152 /// let s = "Löwe 老虎 Léopard";
1153 /// let x: &[_] = &['1', '2'];
1155 /// assert_eq!(s.find(x), None);
1157 #[stable(feature = "rust1", since = "1.0.0")]
1159 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1160 pat.into_searcher(self).next_match().map(|(i, _)| i)
1163 /// Returns the byte index for the first character of the last match of the pattern in
1164 /// this string slice.
1166 /// Returns [`None`] if the pattern doesn't match.
1168 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1169 /// function or closure that determines if a character matches.
1171 /// [`char`]: prim@char
1172 /// [pattern]: self::pattern
1176 /// Simple patterns:
1179 /// let s = "Löwe 老虎 Léopard Gepardi";
1181 /// assert_eq!(s.rfind('L'), Some(13));
1182 /// assert_eq!(s.rfind('é'), Some(14));
1183 /// assert_eq!(s.rfind("pard"), Some(24));
1186 /// More complex patterns with closures:
1189 /// let s = "Löwe 老虎 Léopard";
1191 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1192 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1195 /// Not finding the pattern:
1198 /// let s = "Löwe 老虎 Léopard";
1199 /// let x: &[_] = &['1', '2'];
1201 /// assert_eq!(s.rfind(x), None);
1203 #[stable(feature = "rust1", since = "1.0.0")]
1205 pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
1207 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1209 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1212 /// An iterator over substrings of this string slice, separated by
1213 /// characters matched by a pattern.
1215 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1216 /// function or closure that determines if a character matches.
1218 /// [`char`]: prim@char
1219 /// [pattern]: self::pattern
1221 /// # Iterator behavior
1223 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1224 /// allows a reverse search and forward/reverse search yields the same
1225 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1227 /// If the pattern allows a reverse search but its results might differ
1228 /// from a forward search, the [`rsplit`] method can be used.
1230 /// [`rsplit`]: str::rsplit
1234 /// Simple patterns:
1237 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1238 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1240 /// let v: Vec<&str> = "".split('X').collect();
1241 /// assert_eq!(v, [""]);
1243 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1244 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1246 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1247 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1249 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1250 /// assert_eq!(v, ["abc", "def", "ghi"]);
1252 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1253 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1256 /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1259 /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1260 /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1263 /// A more complex pattern, using a closure:
1266 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1267 /// assert_eq!(v, ["abc", "def", "ghi"]);
1270 /// If a string contains multiple contiguous separators, you will end up
1271 /// with empty strings in the output:
1274 /// let x = "||||a||b|c".to_string();
1275 /// let d: Vec<_> = x.split('|').collect();
1277 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1280 /// Contiguous separators are separated by the empty string.
1283 /// let x = "(///)".to_string();
1284 /// let d: Vec<_> = x.split('/').collect();
1286 /// assert_eq!(d, &["(", "", "", ")"]);
1289 /// Separators at the start or end of a string are neighbored
1290 /// by empty strings.
1293 /// let d: Vec<_> = "010".split("0").collect();
1294 /// assert_eq!(d, &["", "1", ""]);
1297 /// When the empty string is used as a separator, it separates
1298 /// every character in the string, along with the beginning
1299 /// and end of the string.
1302 /// let f: Vec<_> = "rust".split("").collect();
1303 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1306 /// Contiguous separators can lead to possibly surprising behavior
1307 /// when whitespace is used as the separator. This code is correct:
1310 /// let x = " a b c".to_string();
1311 /// let d: Vec<_> = x.split(' ').collect();
1313 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1316 /// It does _not_ give you:
1319 /// assert_eq!(d, &["a", "b", "c"]);
1322 /// Use [`split_whitespace`] for this behavior.
1324 /// [`split_whitespace`]: str::split_whitespace
1325 #[stable(feature = "rust1", since = "1.0.0")]
1327 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1328 Split(SplitInternal {
1331 matcher: pat.into_searcher(self),
1332 allow_trailing_empty: true,
1337 /// An iterator over substrings of this string slice, separated by
1338 /// characters matched by a pattern. Differs from the iterator produced by
1339 /// `split` in that `split_inclusive` leaves the matched part as the
1340 /// terminator of the substring.
1342 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1343 /// function or closure that determines if a character matches.
1345 /// [`char`]: prim@char
1346 /// [pattern]: self::pattern
1351 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1352 /// .split_inclusive('\n').collect();
1353 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1356 /// If the last element of the string is matched,
1357 /// that element will be considered the terminator of the preceding substring.
1358 /// That substring will be the last item returned by the iterator.
1361 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1362 /// .split_inclusive('\n').collect();
1363 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1365 #[stable(feature = "split_inclusive", since = "1.51.0")]
1367 pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> {
1368 SplitInclusive(SplitInternal {
1371 matcher: pat.into_searcher(self),
1372 allow_trailing_empty: false,
1377 /// An iterator over substrings of the given string slice, separated by
1378 /// characters matched by a pattern and yielded in reverse order.
1380 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1381 /// function or closure that determines if a character matches.
1383 /// [`char`]: prim@char
1384 /// [pattern]: self::pattern
1386 /// # Iterator behavior
1388 /// The returned iterator requires that the pattern supports a reverse
1389 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1390 /// search yields the same elements.
1392 /// For iterating from the front, the [`split`] method can be used.
1394 /// [`split`]: str::split
1398 /// Simple patterns:
1401 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1402 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1404 /// let v: Vec<&str> = "".rsplit('X').collect();
1405 /// assert_eq!(v, [""]);
1407 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1408 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1410 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1411 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1414 /// A more complex pattern, using a closure:
1417 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1418 /// assert_eq!(v, ["ghi", "def", "abc"]);
1420 #[stable(feature = "rust1", since = "1.0.0")]
1422 pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>
1424 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1426 RSplit(self.split(pat).0)
1429 /// An iterator over substrings of the given string slice, separated by
1430 /// characters matched by a pattern.
1432 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1433 /// function or closure that determines if a character matches.
1435 /// [`char`]: prim@char
1436 /// [pattern]: self::pattern
1438 /// Equivalent to [`split`], except that the trailing substring
1439 /// is skipped if empty.
1441 /// [`split`]: str::split
1443 /// This method can be used for string data that is _terminated_,
1444 /// rather than _separated_ by a pattern.
1446 /// # Iterator behavior
1448 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1449 /// allows a reverse search and forward/reverse search yields the same
1450 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1452 /// If the pattern allows a reverse search but its results might differ
1453 /// from a forward search, the [`rsplit_terminator`] method can be used.
1455 /// [`rsplit_terminator`]: str::rsplit_terminator
1462 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1463 /// assert_eq!(v, ["A", "B"]);
1465 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1466 /// assert_eq!(v, ["A", "", "B", ""]);
1468 /// let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
1469 /// assert_eq!(v, ["A", "B", "C", "D"]);
1471 #[stable(feature = "rust1", since = "1.0.0")]
1473 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1474 SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1477 /// An iterator over substrings of `self`, separated by characters
1478 /// matched by a pattern and yielded in reverse order.
1480 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1481 /// function or closure that determines if a character matches.
1483 /// [`char`]: prim@char
1484 /// [pattern]: self::pattern
1486 /// Equivalent to [`split`], except that the trailing substring is
1487 /// skipped if empty.
1489 /// [`split`]: str::split
1491 /// This method can be used for string data that is _terminated_,
1492 /// rather than _separated_ by a pattern.
1494 /// # Iterator behavior
1496 /// The returned iterator requires that the pattern supports a
1497 /// reverse search, and it will be double ended if a forward/reverse
1498 /// search yields the same elements.
1500 /// For iterating from the front, the [`split_terminator`] method can be
1503 /// [`split_terminator`]: str::split_terminator
1508 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1509 /// assert_eq!(v, ["B", "A"]);
1511 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1512 /// assert_eq!(v, ["", "B", "", "A"]);
1514 /// let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
1515 /// assert_eq!(v, ["D", "C", "B", "A"]);
1517 #[stable(feature = "rust1", since = "1.0.0")]
1519 pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1521 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1523 RSplitTerminator(self.split_terminator(pat).0)
1526 /// An iterator over substrings of the given string slice, separated by a
1527 /// pattern, restricted to returning at most `n` items.
1529 /// If `n` substrings are returned, the last substring (the `n`th substring)
1530 /// will contain the remainder of the string.
1532 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1533 /// function or closure that determines if a character matches.
1535 /// [`char`]: prim@char
1536 /// [pattern]: self::pattern
1538 /// # Iterator behavior
1540 /// The returned iterator will not be double ended, because it is
1541 /// not efficient to support.
1543 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1546 /// [`rsplitn`]: str::rsplitn
1550 /// Simple patterns:
1553 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1554 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1556 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1557 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1559 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1560 /// assert_eq!(v, ["abcXdef"]);
1562 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1563 /// assert_eq!(v, [""]);
1566 /// A more complex pattern, using a closure:
1569 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1570 /// assert_eq!(v, ["abc", "defXghi"]);
1572 #[stable(feature = "rust1", since = "1.0.0")]
1574 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1575 SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1578 /// An iterator over substrings of this string slice, separated by a
1579 /// pattern, starting from the end of the string, restricted to returning
1580 /// at most `n` items.
1582 /// If `n` substrings are returned, the last substring (the `n`th substring)
1583 /// will contain the remainder of the string.
1585 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1586 /// function or closure that determines if a character matches.
1588 /// [`char`]: prim@char
1589 /// [pattern]: self::pattern
1591 /// # Iterator behavior
1593 /// The returned iterator will not be double ended, because it is not
1594 /// efficient to support.
1596 /// For splitting from the front, the [`splitn`] method can be used.
1598 /// [`splitn`]: str::splitn
1602 /// Simple patterns:
1605 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1606 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1608 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1609 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1611 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1612 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1615 /// A more complex pattern, using a closure:
1618 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1619 /// assert_eq!(v, ["ghi", "abc1def"]);
1621 #[stable(feature = "rust1", since = "1.0.0")]
1623 pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1625 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1627 RSplitN(self.splitn(n, pat).0)
1630 /// Splits the string on the first occurrence of the specified delimiter and
1631 /// returns prefix before delimiter and suffix after delimiter.
1636 /// assert_eq!("cfg".split_once('='), None);
1637 /// assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
1638 /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1639 /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1641 #[stable(feature = "str_split_once", since = "1.52.0")]
1643 pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> {
1644 let (start, end) = delimiter.into_searcher(self).next_match()?;
1645 // SAFETY: `Searcher` is known to return valid indices.
1646 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1649 /// Splits the string on the last occurrence of the specified delimiter and
1650 /// returns prefix before delimiter and suffix after delimiter.
1655 /// assert_eq!("cfg".rsplit_once('='), None);
1656 /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
1657 /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1659 #[stable(feature = "str_split_once", since = "1.52.0")]
1661 pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
1663 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1665 let (start, end) = delimiter.into_searcher(self).next_match_back()?;
1666 // SAFETY: `Searcher` is known to return valid indices.
1667 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1670 /// An iterator over the disjoint matches of a pattern within the given string
1673 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1674 /// function or closure that determines if a character matches.
1676 /// [`char`]: prim@char
1677 /// [pattern]: self::pattern
1679 /// # Iterator behavior
1681 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1682 /// allows a reverse search and forward/reverse search yields the same
1683 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1685 /// If the pattern allows a reverse search but its results might differ
1686 /// from a forward search, the [`rmatches`] method can be used.
1688 /// [`rmatches`]: str::matches
1695 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1696 /// assert_eq!(v, ["abc", "abc", "abc"]);
1698 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1699 /// assert_eq!(v, ["1", "2", "3"]);
1701 #[stable(feature = "str_matches", since = "1.2.0")]
1703 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1704 Matches(MatchesInternal(pat.into_searcher(self)))
1707 /// An iterator over the disjoint matches of a pattern within this string slice,
1708 /// yielded in reverse order.
1710 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1711 /// function or closure that determines if a character matches.
1713 /// [`char`]: prim@char
1714 /// [pattern]: self::pattern
1716 /// # Iterator behavior
1718 /// The returned iterator requires that the pattern supports a reverse
1719 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1720 /// search yields the same elements.
1722 /// For iterating from the front, the [`matches`] method can be used.
1724 /// [`matches`]: str::matches
1731 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1732 /// assert_eq!(v, ["abc", "abc", "abc"]);
1734 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1735 /// assert_eq!(v, ["3", "2", "1"]);
1737 #[stable(feature = "str_matches", since = "1.2.0")]
1739 pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>
1741 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1743 RMatches(self.matches(pat).0)
1746 /// An iterator over the disjoint matches of a pattern within this string
1747 /// slice as well as the index that the match starts at.
1749 /// For matches of `pat` within `self` that overlap, only the indices
1750 /// corresponding to the first match are returned.
1752 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1753 /// function or closure that determines if a character matches.
1755 /// [`char`]: prim@char
1756 /// [pattern]: self::pattern
1758 /// # Iterator behavior
1760 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1761 /// allows a reverse search and forward/reverse search yields the same
1762 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1764 /// If the pattern allows a reverse search but its results might differ
1765 /// from a forward search, the [`rmatch_indices`] method can be used.
1767 /// [`rmatch_indices`]: str::rmatch_indices
1774 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1775 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1777 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1778 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1780 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1781 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1783 #[stable(feature = "str_match_indices", since = "1.5.0")]
1785 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1786 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1789 /// An iterator over the disjoint matches of a pattern within `self`,
1790 /// yielded in reverse order along with the index of the match.
1792 /// For matches of `pat` within `self` that overlap, only the indices
1793 /// corresponding to the last match are returned.
1795 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1796 /// function or closure that determines if a character matches.
1798 /// [`char`]: prim@char
1799 /// [pattern]: self::pattern
1801 /// # Iterator behavior
1803 /// The returned iterator requires that the pattern supports a reverse
1804 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1805 /// search yields the same elements.
1807 /// For iterating from the front, the [`match_indices`] method can be used.
1809 /// [`match_indices`]: str::match_indices
1816 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1817 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1819 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1820 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1822 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1823 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1825 #[stable(feature = "str_match_indices", since = "1.5.0")]
1827 pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>
1829 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1831 RMatchIndices(self.match_indices(pat).0)
1834 /// Returns a string slice with leading and trailing whitespace removed.
1836 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1837 /// Core Property `White_Space`, which includes newlines.
1844 /// let s = "\n Hello\tworld\t\n";
1846 /// assert_eq!("Hello\tworld", s.trim());
1849 #[must_use = "this returns the trimmed string as a slice, \
1850 without modifying the original"]
1851 #[stable(feature = "rust1", since = "1.0.0")]
1852 #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim")]
1853 pub fn trim(&self) -> &str {
1854 self.trim_matches(|c: char| c.is_whitespace())
1857 /// Returns a string slice with leading whitespace removed.
1859 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1860 /// Core Property `White_Space`, which includes newlines.
1862 /// # Text directionality
1864 /// A string is a sequence of bytes. `start` in this context means the first
1865 /// position of that byte string; for a left-to-right language like English or
1866 /// Russian, this will be left side, and for right-to-left languages like
1867 /// Arabic or Hebrew, this will be the right side.
1874 /// let s = "\n Hello\tworld\t\n";
1875 /// assert_eq!("Hello\tworld\t\n", s.trim_start());
1881 /// let s = " English ";
1882 /// assert!(Some('E') == s.trim_start().chars().next());
1884 /// let s = " עברית ";
1885 /// assert!(Some('ע') == s.trim_start().chars().next());
1888 #[must_use = "this returns the trimmed string as a new slice, \
1889 without modifying the original"]
1890 #[stable(feature = "trim_direction", since = "1.30.0")]
1891 #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim_start")]
1892 pub fn trim_start(&self) -> &str {
1893 self.trim_start_matches(|c: char| c.is_whitespace())
1896 /// Returns a string slice with trailing whitespace removed.
1898 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1899 /// Core Property `White_Space`, which includes newlines.
1901 /// # Text directionality
1903 /// A string is a sequence of bytes. `end` in this context means the last
1904 /// position of that byte string; for a left-to-right language like English or
1905 /// Russian, this will be right side, and for right-to-left languages like
1906 /// Arabic or Hebrew, this will be the left side.
1913 /// let s = "\n Hello\tworld\t\n";
1914 /// assert_eq!("\n Hello\tworld", s.trim_end());
1920 /// let s = " English ";
1921 /// assert!(Some('h') == s.trim_end().chars().rev().next());
1923 /// let s = " עברית ";
1924 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
1927 #[must_use = "this returns the trimmed string as a new slice, \
1928 without modifying the original"]
1929 #[stable(feature = "trim_direction", since = "1.30.0")]
1930 #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim_end")]
1931 pub fn trim_end(&self) -> &str {
1932 self.trim_end_matches(|c: char| c.is_whitespace())
1935 /// Returns a string slice with leading whitespace removed.
1937 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1938 /// Core Property `White_Space`.
1940 /// # Text directionality
1942 /// A string is a sequence of bytes. 'Left' in this context means the first
1943 /// position of that byte string; for a language like Arabic or Hebrew
1944 /// which are 'right to left' rather than 'left to right', this will be
1945 /// the _right_ side, not the left.
1952 /// let s = " Hello\tworld\t";
1954 /// assert_eq!("Hello\tworld\t", s.trim_left());
1960 /// let s = " English";
1961 /// assert!(Some('E') == s.trim_left().chars().next());
1963 /// let s = " עברית";
1964 /// assert!(Some('ע') == s.trim_left().chars().next());
1966 #[must_use = "this returns the trimmed string as a new slice, \
1967 without modifying the original"]
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 #[deprecated(since = "1.33.0", note = "superseded by `trim_start`", suggestion = "trim_start")]
1971 pub fn trim_left(&self) -> &str {
1975 /// Returns a string slice with trailing whitespace removed.
1977 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1978 /// Core Property `White_Space`.
1980 /// # Text directionality
1982 /// A string is a sequence of bytes. 'Right' in this context means the last
1983 /// position of that byte string; for a language like Arabic or Hebrew
1984 /// which are 'right to left' rather than 'left to right', this will be
1985 /// the _left_ side, not the right.
1992 /// let s = " Hello\tworld\t";
1994 /// assert_eq!(" Hello\tworld", s.trim_right());
2000 /// let s = "English ";
2001 /// assert!(Some('h') == s.trim_right().chars().rev().next());
2003 /// let s = "עברית ";
2004 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
2006 #[must_use = "this returns the trimmed string as a new slice, \
2007 without modifying the original"]
2009 #[stable(feature = "rust1", since = "1.0.0")]
2010 #[deprecated(since = "1.33.0", note = "superseded by `trim_end`", suggestion = "trim_end")]
2011 pub fn trim_right(&self) -> &str {
2015 /// Returns a string slice with all prefixes and suffixes that match a
2016 /// pattern repeatedly removed.
2018 /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
2019 /// or closure that determines if a character matches.
2021 /// [`char`]: prim@char
2022 /// [pattern]: self::pattern
2026 /// Simple patterns:
2029 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
2030 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
2032 /// let x: &[_] = &['1', '2'];
2033 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
2036 /// A more complex pattern, using a closure:
2039 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
2041 #[must_use = "this returns the trimmed string as a new slice, \
2042 without modifying the original"]
2043 #[stable(feature = "rust1", since = "1.0.0")]
2044 pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
2046 P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
2050 let mut matcher = pat.into_searcher(self);
2051 if let Some((a, b)) = matcher.next_reject() {
2053 j = b; // Remember earliest known match, correct it below if
2054 // last match is different
2056 if let Some((_, b)) = matcher.next_reject_back() {
2059 // SAFETY: `Searcher` is known to return valid indices.
2060 unsafe { self.get_unchecked(i..j) }
2063 /// Returns a string slice with all prefixes that match a pattern
2064 /// repeatedly removed.
2066 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2067 /// function or closure that determines if a character matches.
2069 /// [`char`]: prim@char
2070 /// [pattern]: self::pattern
2072 /// # Text directionality
2074 /// A string is a sequence of bytes. `start` in this context means the first
2075 /// position of that byte string; for a left-to-right language like English or
2076 /// Russian, this will be left side, and for right-to-left languages like
2077 /// Arabic or Hebrew, this will be the right side.
2084 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
2085 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
2087 /// let x: &[_] = &['1', '2'];
2088 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
2090 #[must_use = "this returns the trimmed string as a new slice, \
2091 without modifying the original"]
2092 #[stable(feature = "trim_direction", since = "1.30.0")]
2093 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2094 let mut i = self.len();
2095 let mut matcher = pat.into_searcher(self);
2096 if let Some((a, _)) = matcher.next_reject() {
2099 // SAFETY: `Searcher` is known to return valid indices.
2100 unsafe { self.get_unchecked(i..self.len()) }
2103 /// Returns a string slice with the prefix removed.
2105 /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped
2106 /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once.
2108 /// If the string does not start with `prefix`, returns `None`.
2110 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2111 /// function or closure that determines if a character matches.
2113 /// [`char`]: prim@char
2114 /// [pattern]: self::pattern
2119 /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2120 /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2121 /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2123 #[must_use = "this returns the remaining substring as a new slice, \
2124 without modifying the original"]
2125 #[stable(feature = "str_strip", since = "1.45.0")]
2126 pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> {
2127 prefix.strip_prefix_of(self)
2130 /// Returns a string slice with the suffix removed.
2132 /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2133 /// wrapped in `Some`. Unlike `trim_end_matches`, this method removes the suffix exactly once.
2135 /// If the string does not end with `suffix`, returns `None`.
2137 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2138 /// function or closure that determines if a character matches.
2140 /// [`char`]: prim@char
2141 /// [pattern]: self::pattern
2146 /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2147 /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2148 /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2150 #[must_use = "this returns the remaining substring as a new slice, \
2151 without modifying the original"]
2152 #[stable(feature = "str_strip", since = "1.45.0")]
2153 pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
2156 <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
2158 suffix.strip_suffix_of(self)
2161 /// Returns a string slice with all suffixes that match a pattern
2162 /// repeatedly removed.
2164 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2165 /// function or closure that determines if a character matches.
2167 /// [`char`]: prim@char
2168 /// [pattern]: self::pattern
2170 /// # Text directionality
2172 /// A string is a sequence of bytes. `end` in this context means the last
2173 /// position of that byte string; for a left-to-right language like English or
2174 /// Russian, this will be right side, and for right-to-left languages like
2175 /// Arabic or Hebrew, this will be the left side.
2179 /// Simple patterns:
2182 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2183 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2185 /// let x: &[_] = &['1', '2'];
2186 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2189 /// A more complex pattern, using a closure:
2192 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2194 #[must_use = "this returns the trimmed string as a new slice, \
2195 without modifying the original"]
2196 #[stable(feature = "trim_direction", since = "1.30.0")]
2197 pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
2199 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2202 let mut matcher = pat.into_searcher(self);
2203 if let Some((_, b)) = matcher.next_reject_back() {
2206 // SAFETY: `Searcher` is known to return valid indices.
2207 unsafe { self.get_unchecked(0..j) }
2210 /// Returns a string slice with all prefixes that match a pattern
2211 /// repeatedly removed.
2213 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2214 /// function or closure that determines if a character matches.
2216 /// [`char`]: prim@char
2217 /// [pattern]: self::pattern
2219 /// # Text directionality
2221 /// A string is a sequence of bytes. 'Left' in this context means the first
2222 /// position of that byte string; for a language like Arabic or Hebrew
2223 /// which are 'right to left' rather than 'left to right', this will be
2224 /// the _right_ side, not the left.
2231 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2232 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2234 /// let x: &[_] = &['1', '2'];
2235 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2237 #[stable(feature = "rust1", since = "1.0.0")]
2240 note = "superseded by `trim_start_matches`",
2241 suggestion = "trim_start_matches"
2243 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2244 self.trim_start_matches(pat)
2247 /// Returns a string slice with all suffixes that match a pattern
2248 /// repeatedly removed.
2250 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2251 /// function or closure that determines if a character matches.
2253 /// [`char`]: prim@char
2254 /// [pattern]: self::pattern
2256 /// # Text directionality
2258 /// A string is a sequence of bytes. 'Right' in this context means the last
2259 /// position of that byte string; for a language like Arabic or Hebrew
2260 /// which are 'right to left' rather than 'left to right', this will be
2261 /// the _left_ side, not the right.
2265 /// Simple patterns:
2268 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2269 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2271 /// let x: &[_] = &['1', '2'];
2272 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2275 /// A more complex pattern, using a closure:
2278 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2280 #[stable(feature = "rust1", since = "1.0.0")]
2283 note = "superseded by `trim_end_matches`",
2284 suggestion = "trim_end_matches"
2286 pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
2288 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2290 self.trim_end_matches(pat)
2293 /// Parses this string slice into another type.
2295 /// Because `parse` is so general, it can cause problems with type
2296 /// inference. As such, `parse` is one of the few times you'll see
2297 /// the syntax affectionately known as the 'turbofish': `::<>`. This
2298 /// helps the inference algorithm understand specifically which type
2299 /// you're trying to parse into.
2301 /// `parse` can parse into any type that implements the [`FromStr`] trait.
2306 /// Will return [`Err`] if it's not possible to parse this string slice into
2307 /// the desired type.
2309 /// [`Err`]: FromStr::Err
2316 /// let four: u32 = "4".parse().unwrap();
2318 /// assert_eq!(4, four);
2321 /// Using the 'turbofish' instead of annotating `four`:
2324 /// let four = "4".parse::<u32>();
2326 /// assert_eq!(Ok(4), four);
2329 /// Failing to parse:
2332 /// let nope = "j".parse::<u32>();
2334 /// assert!(nope.is_err());
2337 #[stable(feature = "rust1", since = "1.0.0")]
2338 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2339 FromStr::from_str(self)
2342 /// Checks if all characters in this string are within the ASCII range.
2347 /// let ascii = "hello!\n";
2348 /// let non_ascii = "Grüße, Jürgen ❤";
2350 /// assert!(ascii.is_ascii());
2351 /// assert!(!non_ascii.is_ascii());
2353 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2356 pub fn is_ascii(&self) -> bool {
2357 // We can treat each byte as character here: all multibyte characters
2358 // start with a byte that is not in the ASCII range, so we will stop
2360 self.as_bytes().is_ascii()
2363 /// Checks that two strings are an ASCII case-insensitive match.
2365 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2366 /// but without allocating and copying temporaries.
2371 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2372 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2373 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2375 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2378 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2379 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2382 /// Converts this string to its ASCII upper case equivalent in-place.
2384 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2385 /// but non-ASCII letters are unchanged.
2387 /// To return a new uppercased value without modifying the existing one, use
2388 /// [`to_ascii_uppercase()`].
2390 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2395 /// let mut s = String::from("Grüße, Jürgen ❤");
2397 /// s.make_ascii_uppercase();
2399 /// assert_eq!("GRüßE, JüRGEN ❤", s);
2401 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2403 pub fn make_ascii_uppercase(&mut self) {
2404 // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2405 let me = unsafe { self.as_bytes_mut() };
2406 me.make_ascii_uppercase()
2409 /// Converts this string to its ASCII lower case equivalent in-place.
2411 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2412 /// but non-ASCII letters are unchanged.
2414 /// To return a new lowercased value without modifying the existing one, use
2415 /// [`to_ascii_lowercase()`].
2417 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2422 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2424 /// s.make_ascii_lowercase();
2426 /// assert_eq!("grÜße, jÜrgen ❤", s);
2428 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2430 pub fn make_ascii_lowercase(&mut self) {
2431 // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2432 let me = unsafe { self.as_bytes_mut() };
2433 me.make_ascii_lowercase()
2436 /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
2438 /// Note: only extended grapheme codepoints that begin the string will be
2446 /// for c in "❤\n!".escape_debug() {
2452 /// Using `println!` directly:
2455 /// println!("{}", "❤\n!".escape_debug());
2459 /// Both are equivalent to:
2462 /// println!("❤\\n!");
2465 /// Using `to_string`:
2468 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
2470 #[must_use = "this returns the escaped string as an iterator, \
2471 without modifying the original"]
2472 #[stable(feature = "str_escape", since = "1.34.0")]
2473 pub fn escape_debug(&self) -> EscapeDebug<'_> {
2474 let mut chars = self.chars();
2478 .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL))
2481 .chain(chars.flat_map(CharEscapeDebugContinue)),
2485 /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
2492 /// for c in "❤\n!".escape_default() {
2498 /// Using `println!` directly:
2501 /// println!("{}", "❤\n!".escape_default());
2505 /// Both are equivalent to:
2508 /// println!("\\u{{2764}}\\n!");
2511 /// Using `to_string`:
2514 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
2516 #[must_use = "this returns the escaped string as an iterator, \
2517 without modifying the original"]
2518 #[stable(feature = "str_escape", since = "1.34.0")]
2519 pub fn escape_default(&self) -> EscapeDefault<'_> {
2520 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
2523 /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
2530 /// for c in "❤\n!".escape_unicode() {
2536 /// Using `println!` directly:
2539 /// println!("{}", "❤\n!".escape_unicode());
2543 /// Both are equivalent to:
2546 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
2549 /// Using `to_string`:
2552 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
2554 #[must_use = "this returns the escaped string as an iterator, \
2555 without modifying the original"]
2556 #[stable(feature = "str_escape", since = "1.34.0")]
2557 pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
2558 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
2562 #[stable(feature = "rust1", since = "1.0.0")]
2563 impl AsRef<[u8]> for str {
2565 fn as_ref(&self) -> &[u8] {
2570 #[stable(feature = "rust1", since = "1.0.0")]
2571 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
2572 impl const Default for &str {
2573 /// Creates an empty str
2575 fn default() -> Self {
2580 #[stable(feature = "default_mut_str", since = "1.28.0")]
2581 impl Default for &mut str {
2582 /// Creates an empty mutable str
2584 fn default() -> Self {
2585 // SAFETY: The empty string is valid UTF-8.
2586 unsafe { from_utf8_unchecked_mut(&mut []) }
2591 /// A nameable, cloneable fn type
2593 struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
2595 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
2600 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
2601 c.escape_debug_ext(EscapeDebugExtArgs {
2602 escape_grapheme_extended: false,
2603 escape_single_quote: true,
2604 escape_double_quote: true
2609 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
2613 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
2618 struct IsWhitespace impl Fn = |c: char| -> bool {
2623 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
2624 byte.is_ascii_whitespace()
2628 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
2633 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
2638 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
2640 unsafe { from_utf8_unchecked(bytes) }
2644 #[stable(feature = "rust1", since = "1.0.0")]
2645 impl !crate::error::Error for &str {}