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(
94 const fn slice_error_fail_ct(_: &str, _: usize, _: usize) -> ! {
95 panic!("failed to slice string");
98 fn slice_error_fail_rt(s: &str, begin: usize, end: usize) -> ! {
99 const MAX_DISPLAY_LENGTH: usize = 256;
100 let trunc_len = s.floor_char_boundary(MAX_DISPLAY_LENGTH);
101 let s_trunc = &s[..trunc_len];
102 let ellipsis = if trunc_len < s.len() { "[...]" } else { "" };
105 if begin > s.len() || end > s.len() {
106 let oob_index = if begin > s.len() { begin } else { end };
107 panic!("byte index {oob_index} is out of bounds of `{s_trunc}`{ellipsis}");
113 "begin <= end ({} <= {}) when slicing `{}`{}",
120 // 3. character boundary
121 let index = if !s.is_char_boundary(begin) { begin } else { end };
122 // find the character
123 let char_start = s.floor_char_boundary(index);
124 // `char_start` must be less than len and a char boundary
125 let ch = s[char_start..].chars().next().unwrap();
126 let char_range = char_start..char_start + ch.len_utf8();
128 "byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
129 index, ch, char_range, s_trunc, ellipsis
135 /// Returns the length of `self`.
137 /// This length is in bytes, not [`char`]s or graphemes. In other words,
138 /// it might not be what a human considers the length of the string.
140 /// [`char`]: prim@char
147 /// let len = "foo".len();
148 /// assert_eq!(3, len);
150 /// assert_eq!("ƒoo".len(), 4); // fancy f!
151 /// assert_eq!("ƒoo".chars().count(), 3);
153 #[stable(feature = "rust1", since = "1.0.0")]
154 #[rustc_const_stable(feature = "const_str_len", since = "1.39.0")]
157 pub const fn len(&self) -> usize {
158 self.as_bytes().len()
161 /// Returns `true` if `self` has a length of zero bytes.
169 /// assert!(s.is_empty());
171 /// let s = "not empty";
172 /// assert!(!s.is_empty());
174 #[stable(feature = "rust1", since = "1.0.0")]
175 #[rustc_const_stable(feature = "const_str_is_empty", since = "1.39.0")]
178 pub const fn is_empty(&self) -> bool {
182 /// Checks that `index`-th byte is the first byte in a UTF-8 code point
183 /// sequence or the end of the string.
185 /// The start and end of the string (when `index == self.len()`) are
186 /// considered to be boundaries.
188 /// Returns `false` if `index` is greater than `self.len()`.
193 /// let s = "Löwe 老虎 Léopard";
194 /// assert!(s.is_char_boundary(0));
196 /// assert!(s.is_char_boundary(6));
197 /// assert!(s.is_char_boundary(s.len()));
199 /// // second byte of `ö`
200 /// assert!(!s.is_char_boundary(2));
202 /// // third byte of `老`
203 /// assert!(!s.is_char_boundary(8));
206 #[stable(feature = "is_char_boundary", since = "1.9.0")]
207 #[rustc_const_unstable(feature = "const_is_char_boundary", issue = "none")]
209 pub const fn is_char_boundary(&self, index: usize) -> bool {
211 // Test for 0 explicitly so that it can optimize out the check
212 // easily and skip reading string data for that case.
213 // Note that optimizing `self.get(..index)` relies on this.
218 match self.as_bytes().get(index) {
219 // For `None` we have two options:
221 // - index == self.len()
222 // Empty strings are valid, so return true
223 // - index > self.len()
224 // In this case return false
226 // The check is placed exactly here, because it improves generated
227 // code on higher opt-levels. See PR #84751 for more details.
228 None => index == self.len(),
230 Some(&b) => b.is_utf8_char_boundary(),
234 /// Finds the closest `x` not exceeding `index` where `is_char_boundary(x)` is `true`.
236 /// This method can help you truncate a string so that it's still valid UTF-8, but doesn't
237 /// exceed a given number of bytes. Note that this is done purely at the character level
238 /// and can still visually split graphemes, even though the underlying characters aren't
239 /// split. For example, the emoji 🧑🔬 (scientist) could be split so that the string only
240 /// includes 🧑 (person) instead.
245 /// #![feature(round_char_boundary)]
246 /// let s = "❤️🧡💛💚💙💜";
247 /// assert_eq!(s.len(), 26);
248 /// assert!(!s.is_char_boundary(13));
250 /// let closest = s.floor_char_boundary(13);
251 /// assert_eq!(closest, 10);
252 /// assert_eq!(&s[..closest], "❤️🧡");
254 #[unstable(feature = "round_char_boundary", issue = "93743")]
256 pub fn floor_char_boundary(&self, index: usize) -> usize {
257 if index >= self.len() {
260 let lower_bound = index.saturating_sub(3);
261 let new_index = self.as_bytes()[lower_bound..=index]
263 .rposition(|b| b.is_utf8_char_boundary());
265 // SAFETY: we know that the character boundary will be within four bytes
266 unsafe { lower_bound + new_index.unwrap_unchecked() }
270 /// Finds the closest `x` not below `index` where `is_char_boundary(x)` is `true`.
272 /// This method is the natural complement to [`floor_char_boundary`]. See that method
273 /// for more details.
275 /// [`floor_char_boundary`]: str::floor_char_boundary
279 /// Panics if `index > self.len()`.
284 /// #![feature(round_char_boundary)]
285 /// let s = "❤️🧡💛💚💙💜";
286 /// assert_eq!(s.len(), 26);
287 /// assert!(!s.is_char_boundary(13));
289 /// let closest = s.ceil_char_boundary(13);
290 /// assert_eq!(closest, 14);
291 /// assert_eq!(&s[..closest], "❤️🧡💛");
293 #[unstable(feature = "round_char_boundary", issue = "93743")]
295 pub fn ceil_char_boundary(&self, index: usize) -> usize {
296 if index > self.len() {
297 slice_error_fail(self, index, index)
299 let upper_bound = Ord::min(index + 4, self.len());
300 self.as_bytes()[index..upper_bound]
302 .position(|b| b.is_utf8_char_boundary())
303 .map_or(upper_bound, |pos| pos + index)
307 /// Converts a string slice to a byte slice. To convert the byte slice back
308 /// into a string slice, use the [`from_utf8`] function.
315 /// let bytes = "bors".as_bytes();
316 /// assert_eq!(b"bors", bytes);
318 #[stable(feature = "rust1", since = "1.0.0")]
319 #[rustc_const_stable(feature = "str_as_bytes", since = "1.39.0")]
322 #[allow(unused_attributes)]
323 pub const fn as_bytes(&self) -> &[u8] {
324 // SAFETY: const sound because we transmute two types with the same layout
325 unsafe { mem::transmute(self) }
328 /// Converts a mutable string slice to a mutable byte slice.
332 /// The caller must ensure that the content of the slice is valid UTF-8
333 /// before the borrow ends and the underlying `str` is used.
335 /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
342 /// let mut s = String::from("Hello");
343 /// let bytes = unsafe { s.as_bytes_mut() };
345 /// assert_eq!(b"Hello", bytes);
351 /// let mut s = String::from("🗻∈🌏");
354 /// let bytes = s.as_bytes_mut();
362 /// assert_eq!("🍔∈🌏", s);
364 #[stable(feature = "str_mut_extras", since = "1.20.0")]
367 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
368 // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
369 // has the same layout as `&[u8]` (only libstd can make this guarantee).
370 // The pointer dereference is safe since it comes from a mutable reference which
371 // is guaranteed to be valid for writes.
372 unsafe { &mut *(self as *mut str as *mut [u8]) }
375 /// Converts a string slice to a raw pointer.
377 /// As string slices are a slice of bytes, the raw pointer points to a
378 /// [`u8`]. This pointer will be pointing to the first byte of the string
381 /// The caller must ensure that the returned pointer is never written to.
382 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
384 /// [`as_mut_ptr`]: str::as_mut_ptr
392 /// let ptr = s.as_ptr();
394 #[stable(feature = "rust1", since = "1.0.0")]
395 #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
398 pub const fn as_ptr(&self) -> *const u8 {
399 self as *const str as *const u8
402 /// Converts a mutable string slice to a raw pointer.
404 /// As string slices are a slice of bytes, the raw pointer points to a
405 /// [`u8`]. This pointer will be pointing to the first byte of the string
408 /// It is your responsibility to make sure that the string slice only gets
409 /// modified in a way that it remains valid UTF-8.
410 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
413 pub fn as_mut_ptr(&mut self) -> *mut u8 {
414 self as *mut str as *mut u8
417 /// Returns a subslice of `str`.
419 /// This is the non-panicking alternative to indexing the `str`. Returns
420 /// [`None`] whenever equivalent indexing operation would panic.
425 /// let v = String::from("🗻∈🌏");
427 /// assert_eq!(Some("🗻"), v.get(0..4));
429 /// // indices not on UTF-8 sequence boundaries
430 /// assert!(v.get(1..).is_none());
431 /// assert!(v.get(..8).is_none());
434 /// assert!(v.get(..42).is_none());
436 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
437 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
439 pub const fn get<I: ~const SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
443 /// Returns a mutable subslice of `str`.
445 /// This is the non-panicking alternative to indexing the `str`. Returns
446 /// [`None`] whenever equivalent indexing operation would panic.
451 /// let mut v = String::from("hello");
452 /// // correct length
453 /// assert!(v.get_mut(0..5).is_some());
455 /// assert!(v.get_mut(..42).is_none());
456 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
458 /// assert_eq!("hello", v);
460 /// let s = v.get_mut(0..2);
461 /// let s = s.map(|s| {
462 /// s.make_ascii_uppercase();
465 /// assert_eq!(Some("HE"), s);
467 /// assert_eq!("HEllo", v);
469 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
470 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
472 pub const fn get_mut<I: ~const SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
476 /// Returns an unchecked subslice of `str`.
478 /// This is the unchecked alternative to indexing the `str`.
482 /// Callers of this function are responsible that these preconditions are
485 /// * The starting index must not exceed the ending index;
486 /// * Indexes must be within bounds of the original slice;
487 /// * Indexes must lie on UTF-8 sequence boundaries.
489 /// Failing that, the returned string slice may reference invalid memory or
490 /// violate the invariants communicated by the `str` type.
497 /// assert_eq!("🗻", v.get_unchecked(0..4));
498 /// assert_eq!("∈", v.get_unchecked(4..7));
499 /// assert_eq!("🌏", v.get_unchecked(7..11));
502 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
503 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
505 pub const unsafe fn get_unchecked<I: ~const SliceIndex<str>>(&self, i: I) -> &I::Output {
506 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
507 // the slice is dereferenceable because `self` is a safe reference.
508 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
509 unsafe { &*i.get_unchecked(self) }
512 /// Returns a mutable, unchecked subslice of `str`.
514 /// This is the unchecked alternative to indexing the `str`.
518 /// Callers of this function are responsible that these preconditions are
521 /// * The starting index must not exceed the ending index;
522 /// * Indexes must be within bounds of the original slice;
523 /// * Indexes must lie on UTF-8 sequence boundaries.
525 /// Failing that, the returned string slice may reference invalid memory or
526 /// violate the invariants communicated by the `str` type.
531 /// let mut v = String::from("🗻∈🌏");
533 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
534 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
535 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
538 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
539 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
541 pub const unsafe fn get_unchecked_mut<I: ~const SliceIndex<str>>(
544 ) -> &mut I::Output {
545 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
546 // the slice is dereferenceable because `self` is a safe reference.
547 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
548 unsafe { &mut *i.get_unchecked_mut(self) }
551 /// Creates a string slice from another string slice, bypassing safety
554 /// This is generally not recommended, use with caution! For a safe
555 /// alternative see [`str`] and [`Index`].
557 /// [`Index`]: crate::ops::Index
559 /// This new slice goes from `begin` to `end`, including `begin` but
562 /// To get a mutable string slice instead, see the
563 /// [`slice_mut_unchecked`] method.
565 /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
569 /// Callers of this function are responsible that three preconditions are
572 /// * `begin` must not exceed `end`.
573 /// * `begin` and `end` must be byte positions within the string slice.
574 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
581 /// let s = "Löwe 老虎 Léopard";
584 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
587 /// let s = "Hello, world!";
590 /// assert_eq!("world", s.slice_unchecked(7, 12));
593 #[stable(feature = "rust1", since = "1.0.0")]
594 #[deprecated(since = "1.29.0", note = "use `get_unchecked(begin..end)` instead")]
597 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
598 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
599 // the slice is dereferenceable because `self` is a safe reference.
600 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
601 unsafe { &*(begin..end).get_unchecked(self) }
604 /// Creates a string slice from another string slice, bypassing safety
606 /// This is generally not recommended, use with caution! For a safe
607 /// alternative see [`str`] and [`IndexMut`].
609 /// [`IndexMut`]: crate::ops::IndexMut
611 /// This new slice goes from `begin` to `end`, including `begin` but
614 /// To get an immutable string slice instead, see the
615 /// [`slice_unchecked`] method.
617 /// [`slice_unchecked`]: str::slice_unchecked
621 /// Callers of this function are responsible that three preconditions are
624 /// * `begin` must not exceed `end`.
625 /// * `begin` and `end` must be byte positions within the string slice.
626 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
627 #[stable(feature = "str_slice_mut", since = "1.5.0")]
628 #[deprecated(since = "1.29.0", note = "use `get_unchecked_mut(begin..end)` instead")]
630 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
631 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
632 // the slice is dereferenceable because `self` is a safe reference.
633 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
634 unsafe { &mut *(begin..end).get_unchecked_mut(self) }
637 /// Divide one string slice into two at an index.
639 /// The argument, `mid`, should be a byte offset from the start of the
640 /// string. It must also be on the boundary of a UTF-8 code point.
642 /// The two slices returned go from the start of the string slice to `mid`,
643 /// and from `mid` to the end of the string slice.
645 /// To get mutable string slices instead, see the [`split_at_mut`]
648 /// [`split_at_mut`]: str::split_at_mut
652 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
653 /// past the end of the last code point of the string slice.
660 /// let s = "Per Martin-Löf";
662 /// let (first, last) = s.split_at(3);
664 /// assert_eq!("Per", first);
665 /// assert_eq!(" Martin-Löf", last);
669 #[stable(feature = "str_split_at", since = "1.4.0")]
670 pub fn split_at(&self, mid: usize) -> (&str, &str) {
671 // is_char_boundary checks that the index is in [0, .len()]
672 if self.is_char_boundary(mid) {
673 // SAFETY: just checked that `mid` is on a char boundary.
674 unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) }
676 slice_error_fail(self, 0, mid)
680 /// Divide one mutable string slice into two at an index.
682 /// The argument, `mid`, should be a byte offset from the start of the
683 /// string. It must also be on the boundary of a UTF-8 code point.
685 /// The two slices returned go from the start of the string slice to `mid`,
686 /// and from `mid` to the end of the string slice.
688 /// To get immutable string slices instead, see the [`split_at`] method.
690 /// [`split_at`]: str::split_at
694 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
695 /// past the end of the last code point of the string slice.
702 /// let mut s = "Per Martin-Löf".to_string();
704 /// let (first, last) = s.split_at_mut(3);
705 /// first.make_ascii_uppercase();
706 /// assert_eq!("PER", first);
707 /// assert_eq!(" Martin-Löf", last);
709 /// assert_eq!("PER Martin-Löf", s);
713 #[stable(feature = "str_split_at", since = "1.4.0")]
714 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
715 // is_char_boundary checks that the index is in [0, .len()]
716 if self.is_char_boundary(mid) {
717 let len = self.len();
718 let ptr = self.as_mut_ptr();
719 // SAFETY: just checked that `mid` is on a char boundary.
722 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
723 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
727 slice_error_fail(self, 0, mid)
731 /// Returns an iterator over the [`char`]s of a string slice.
733 /// As a string slice consists of valid UTF-8, we can iterate through a
734 /// string slice by [`char`]. This method returns such an iterator.
736 /// It's important to remember that [`char`] represents a Unicode Scalar
737 /// Value, and might not match your idea of what a 'character' is. Iteration
738 /// over grapheme clusters may be what you actually want. This functionality
739 /// is not provided by Rust's standard library, check crates.io instead.
746 /// let word = "goodbye";
748 /// let count = word.chars().count();
749 /// assert_eq!(7, count);
751 /// let mut chars = word.chars();
753 /// assert_eq!(Some('g'), chars.next());
754 /// assert_eq!(Some('o'), chars.next());
755 /// assert_eq!(Some('o'), chars.next());
756 /// assert_eq!(Some('d'), chars.next());
757 /// assert_eq!(Some('b'), chars.next());
758 /// assert_eq!(Some('y'), chars.next());
759 /// assert_eq!(Some('e'), chars.next());
761 /// assert_eq!(None, chars.next());
764 /// Remember, [`char`]s might not match your intuition about characters:
766 /// [`char`]: prim@char
771 /// let mut chars = y.chars();
773 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
774 /// assert_eq!(Some('\u{0306}'), chars.next());
776 /// assert_eq!(None, chars.next());
778 #[stable(feature = "rust1", since = "1.0.0")]
780 pub fn chars(&self) -> Chars<'_> {
781 Chars { iter: self.as_bytes().iter() }
784 /// Returns an iterator over the [`char`]s of a string slice, and their
787 /// As a string slice consists of valid UTF-8, we can iterate through a
788 /// string slice by [`char`]. This method returns an iterator of both
789 /// these [`char`]s, as well as their byte positions.
791 /// The iterator yields tuples. The position is first, the [`char`] is
799 /// let word = "goodbye";
801 /// let count = word.char_indices().count();
802 /// assert_eq!(7, count);
804 /// let mut char_indices = word.char_indices();
806 /// assert_eq!(Some((0, 'g')), char_indices.next());
807 /// assert_eq!(Some((1, 'o')), char_indices.next());
808 /// assert_eq!(Some((2, 'o')), char_indices.next());
809 /// assert_eq!(Some((3, 'd')), char_indices.next());
810 /// assert_eq!(Some((4, 'b')), char_indices.next());
811 /// assert_eq!(Some((5, 'y')), char_indices.next());
812 /// assert_eq!(Some((6, 'e')), char_indices.next());
814 /// assert_eq!(None, char_indices.next());
817 /// Remember, [`char`]s might not match your intuition about characters:
819 /// [`char`]: prim@char
822 /// let yes = "y̆es";
824 /// let mut char_indices = yes.char_indices();
826 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
827 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
829 /// // note the 3 here - the last character took up two bytes
830 /// assert_eq!(Some((3, 'e')), char_indices.next());
831 /// assert_eq!(Some((4, 's')), char_indices.next());
833 /// assert_eq!(None, char_indices.next());
835 #[stable(feature = "rust1", since = "1.0.0")]
837 pub fn char_indices(&self) -> CharIndices<'_> {
838 CharIndices { front_offset: 0, iter: self.chars() }
841 /// An iterator over the bytes of a string slice.
843 /// As a string slice consists of a sequence of bytes, we can iterate
844 /// through a string slice by byte. This method returns such an iterator.
851 /// let mut bytes = "bors".bytes();
853 /// assert_eq!(Some(b'b'), bytes.next());
854 /// assert_eq!(Some(b'o'), bytes.next());
855 /// assert_eq!(Some(b'r'), bytes.next());
856 /// assert_eq!(Some(b's'), bytes.next());
858 /// assert_eq!(None, bytes.next());
860 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn bytes(&self) -> Bytes<'_> {
863 Bytes(self.as_bytes().iter().copied())
866 /// Splits a string slice by whitespace.
868 /// The iterator returned will return string slices that are sub-slices of
869 /// the original string slice, separated by any amount of whitespace.
871 /// 'Whitespace' is defined according to the terms of the Unicode Derived
872 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
873 /// instead, use [`split_ascii_whitespace`].
875 /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
882 /// let mut iter = "A few words".split_whitespace();
884 /// assert_eq!(Some("A"), iter.next());
885 /// assert_eq!(Some("few"), iter.next());
886 /// assert_eq!(Some("words"), iter.next());
888 /// assert_eq!(None, iter.next());
891 /// All kinds of whitespace are considered:
894 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
895 /// assert_eq!(Some("Mary"), iter.next());
896 /// assert_eq!(Some("had"), iter.next());
897 /// assert_eq!(Some("a"), iter.next());
898 /// assert_eq!(Some("little"), iter.next());
899 /// assert_eq!(Some("lamb"), iter.next());
901 /// assert_eq!(None, iter.next());
903 #[must_use = "this returns the split string as an iterator, \
904 without modifying the original"]
905 #[stable(feature = "split_whitespace", since = "1.1.0")]
906 #[cfg_attr(not(test), rustc_diagnostic_item = "str_split_whitespace")]
908 pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
909 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
912 /// Splits a string slice by ASCII whitespace.
914 /// The iterator returned will return string slices that are sub-slices of
915 /// the original string slice, separated by any amount of ASCII whitespace.
917 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
919 /// [`split_whitespace`]: str::split_whitespace
926 /// let mut iter = "A few words".split_ascii_whitespace();
928 /// assert_eq!(Some("A"), iter.next());
929 /// assert_eq!(Some("few"), iter.next());
930 /// assert_eq!(Some("words"), iter.next());
932 /// assert_eq!(None, iter.next());
935 /// All kinds of ASCII whitespace are considered:
938 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
939 /// assert_eq!(Some("Mary"), iter.next());
940 /// assert_eq!(Some("had"), iter.next());
941 /// assert_eq!(Some("a"), iter.next());
942 /// assert_eq!(Some("little"), iter.next());
943 /// assert_eq!(Some("lamb"), iter.next());
945 /// assert_eq!(None, iter.next());
947 #[must_use = "this returns the split string as an iterator, \
948 without modifying the original"]
949 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
951 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
953 self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
954 SplitAsciiWhitespace { inner }
957 /// An iterator over the lines of a string, as string slices.
959 /// Lines are ended with either a newline (`\n`) or a carriage return with
960 /// a line feed (`\r\n`).
962 /// The final line ending is optional. A string that ends with a final line
963 /// ending will return the same lines as an otherwise identical string
964 /// without a final line ending.
971 /// let text = "foo\r\nbar\n\nbaz\n";
972 /// let mut lines = text.lines();
974 /// assert_eq!(Some("foo"), lines.next());
975 /// assert_eq!(Some("bar"), lines.next());
976 /// assert_eq!(Some(""), lines.next());
977 /// assert_eq!(Some("baz"), lines.next());
979 /// assert_eq!(None, lines.next());
982 /// The final line ending isn't required:
985 /// let text = "foo\nbar\n\r\nbaz";
986 /// let mut lines = text.lines();
988 /// assert_eq!(Some("foo"), lines.next());
989 /// assert_eq!(Some("bar"), lines.next());
990 /// assert_eq!(Some(""), lines.next());
991 /// assert_eq!(Some("baz"), lines.next());
993 /// assert_eq!(None, lines.next());
995 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn lines(&self) -> Lines<'_> {
998 Lines(self.split_terminator('\n').map(LinesAnyMap))
1001 /// An iterator over the lines of a string.
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 #[deprecated(since = "1.4.0", note = "use lines() instead now")]
1005 #[allow(deprecated)]
1006 pub fn lines_any(&self) -> LinesAny<'_> {
1007 LinesAny(self.lines())
1010 /// Returns an iterator of `u16` over the string encoded as UTF-16.
1017 /// let text = "Zażółć gęślą jaźń";
1019 /// let utf8_len = text.len();
1020 /// let utf16_len = text.encode_utf16().count();
1022 /// assert!(utf16_len <= utf8_len);
1024 #[must_use = "this returns the encoded string as an iterator, \
1025 without modifying the original"]
1026 #[stable(feature = "encode_utf16", since = "1.8.0")]
1027 pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
1028 EncodeUtf16 { chars: self.chars(), extra: 0 }
1031 /// Returns `true` if the given pattern matches a sub-slice of
1032 /// this string slice.
1034 /// Returns `false` if it does not.
1036 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1037 /// function or closure that determines if a character matches.
1039 /// [`char`]: prim@char
1040 /// [pattern]: self::pattern
1047 /// let bananas = "bananas";
1049 /// assert!(bananas.contains("nana"));
1050 /// assert!(!bananas.contains("apples"));
1052 #[stable(feature = "rust1", since = "1.0.0")]
1054 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1055 pat.is_contained_in(self)
1058 /// Returns `true` if the given pattern matches a prefix of this
1061 /// Returns `false` if it does not.
1063 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1064 /// function or closure that determines if a character matches.
1066 /// [`char`]: prim@char
1067 /// [pattern]: self::pattern
1074 /// let bananas = "bananas";
1076 /// assert!(bananas.starts_with("bana"));
1077 /// assert!(!bananas.starts_with("nana"));
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
1081 pat.is_prefix_of(self)
1084 /// Returns `true` if the given pattern matches a suffix of this
1087 /// Returns `false` if it does not.
1089 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1090 /// function or closure that determines if a character matches.
1092 /// [`char`]: prim@char
1093 /// [pattern]: self::pattern
1100 /// let bananas = "bananas";
1102 /// assert!(bananas.ends_with("anas"));
1103 /// assert!(!bananas.ends_with("nana"));
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
1108 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1110 pat.is_suffix_of(self)
1113 /// Returns the byte index of the first character of this string slice that
1114 /// matches the pattern.
1116 /// Returns [`None`] if the pattern doesn't match.
1118 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1119 /// function or closure that determines if a character matches.
1121 /// [`char`]: prim@char
1122 /// [pattern]: self::pattern
1126 /// Simple patterns:
1129 /// let s = "Löwe 老虎 Léopard Gepardi";
1131 /// assert_eq!(s.find('L'), Some(0));
1132 /// assert_eq!(s.find('é'), Some(14));
1133 /// assert_eq!(s.find("pard"), Some(17));
1136 /// More complex patterns using point-free style and closures:
1139 /// let s = "Löwe 老虎 Léopard";
1141 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1142 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1143 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1144 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1147 /// Not finding the pattern:
1150 /// let s = "Löwe 老虎 Léopard";
1151 /// let x: &[_] = &['1', '2'];
1153 /// assert_eq!(s.find(x), None);
1155 #[stable(feature = "rust1", since = "1.0.0")]
1157 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1158 pat.into_searcher(self).next_match().map(|(i, _)| i)
1161 /// Returns the byte index for the first character of the last match of the pattern in
1162 /// this string slice.
1164 /// Returns [`None`] if the pattern doesn't match.
1166 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1167 /// function or closure that determines if a character matches.
1169 /// [`char`]: prim@char
1170 /// [pattern]: self::pattern
1174 /// Simple patterns:
1177 /// let s = "Löwe 老虎 Léopard Gepardi";
1179 /// assert_eq!(s.rfind('L'), Some(13));
1180 /// assert_eq!(s.rfind('é'), Some(14));
1181 /// assert_eq!(s.rfind("pard"), Some(24));
1184 /// More complex patterns with closures:
1187 /// let s = "Löwe 老虎 Léopard";
1189 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1190 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1193 /// Not finding the pattern:
1196 /// let s = "Löwe 老虎 Léopard";
1197 /// let x: &[_] = &['1', '2'];
1199 /// assert_eq!(s.rfind(x), None);
1201 #[stable(feature = "rust1", since = "1.0.0")]
1203 pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
1205 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1207 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1210 /// An iterator over substrings of this string slice, separated by
1211 /// characters matched by a pattern.
1213 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1214 /// function or closure that determines if a character matches.
1216 /// [`char`]: prim@char
1217 /// [pattern]: self::pattern
1219 /// # Iterator behavior
1221 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1222 /// allows a reverse search and forward/reverse search yields the same
1223 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1225 /// If the pattern allows a reverse search but its results might differ
1226 /// from a forward search, the [`rsplit`] method can be used.
1228 /// [`rsplit`]: str::rsplit
1232 /// Simple patterns:
1235 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1236 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1238 /// let v: Vec<&str> = "".split('X').collect();
1239 /// assert_eq!(v, [""]);
1241 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1242 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1244 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1245 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1247 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1248 /// assert_eq!(v, ["abc", "def", "ghi"]);
1250 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1251 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1254 /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1257 /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1258 /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1261 /// A more complex pattern, using a closure:
1264 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1265 /// assert_eq!(v, ["abc", "def", "ghi"]);
1268 /// If a string contains multiple contiguous separators, you will end up
1269 /// with empty strings in the output:
1272 /// let x = "||||a||b|c".to_string();
1273 /// let d: Vec<_> = x.split('|').collect();
1275 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1278 /// Contiguous separators are separated by the empty string.
1281 /// let x = "(///)".to_string();
1282 /// let d: Vec<_> = x.split('/').collect();
1284 /// assert_eq!(d, &["(", "", "", ")"]);
1287 /// Separators at the start or end of a string are neighbored
1288 /// by empty strings.
1291 /// let d: Vec<_> = "010".split("0").collect();
1292 /// assert_eq!(d, &["", "1", ""]);
1295 /// When the empty string is used as a separator, it separates
1296 /// every character in the string, along with the beginning
1297 /// and end of the string.
1300 /// let f: Vec<_> = "rust".split("").collect();
1301 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1304 /// Contiguous separators can lead to possibly surprising behavior
1305 /// when whitespace is used as the separator. This code is correct:
1308 /// let x = " a b c".to_string();
1309 /// let d: Vec<_> = x.split(' ').collect();
1311 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1314 /// It does _not_ give you:
1317 /// assert_eq!(d, &["a", "b", "c"]);
1320 /// Use [`split_whitespace`] for this behavior.
1322 /// [`split_whitespace`]: str::split_whitespace
1323 #[stable(feature = "rust1", since = "1.0.0")]
1325 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1326 Split(SplitInternal {
1329 matcher: pat.into_searcher(self),
1330 allow_trailing_empty: true,
1335 /// An iterator over substrings of this string slice, separated by
1336 /// characters matched by a pattern. Differs from the iterator produced by
1337 /// `split` in that `split_inclusive` leaves the matched part as the
1338 /// terminator of the substring.
1340 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1341 /// function or closure that determines if a character matches.
1343 /// [`char`]: prim@char
1344 /// [pattern]: self::pattern
1349 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1350 /// .split_inclusive('\n').collect();
1351 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1354 /// If the last element of the string is matched,
1355 /// that element will be considered the terminator of the preceding substring.
1356 /// That substring will be the last item returned by the iterator.
1359 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1360 /// .split_inclusive('\n').collect();
1361 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1363 #[stable(feature = "split_inclusive", since = "1.51.0")]
1365 pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> {
1366 SplitInclusive(SplitInternal {
1369 matcher: pat.into_searcher(self),
1370 allow_trailing_empty: false,
1375 /// An iterator over substrings of the given string slice, separated by
1376 /// characters matched by a pattern and yielded in reverse order.
1378 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1379 /// function or closure that determines if a character matches.
1381 /// [`char`]: prim@char
1382 /// [pattern]: self::pattern
1384 /// # Iterator behavior
1386 /// The returned iterator requires that the pattern supports a reverse
1387 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1388 /// search yields the same elements.
1390 /// For iterating from the front, the [`split`] method can be used.
1392 /// [`split`]: str::split
1396 /// Simple patterns:
1399 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1400 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1402 /// let v: Vec<&str> = "".rsplit('X').collect();
1403 /// assert_eq!(v, [""]);
1405 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1406 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1408 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1409 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1412 /// A more complex pattern, using a closure:
1415 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1416 /// assert_eq!(v, ["ghi", "def", "abc"]);
1418 #[stable(feature = "rust1", since = "1.0.0")]
1420 pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>
1422 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1424 RSplit(self.split(pat).0)
1427 /// An iterator over substrings of the given string slice, separated by
1428 /// characters matched by a pattern.
1430 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1431 /// function or closure that determines if a character matches.
1433 /// [`char`]: prim@char
1434 /// [pattern]: self::pattern
1436 /// Equivalent to [`split`], except that the trailing substring
1437 /// is skipped if empty.
1439 /// [`split`]: str::split
1441 /// This method can be used for string data that is _terminated_,
1442 /// rather than _separated_ by a pattern.
1444 /// # Iterator behavior
1446 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1447 /// allows a reverse search and forward/reverse search yields the same
1448 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1450 /// If the pattern allows a reverse search but its results might differ
1451 /// from a forward search, the [`rsplit_terminator`] method can be used.
1453 /// [`rsplit_terminator`]: str::rsplit_terminator
1460 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1461 /// assert_eq!(v, ["A", "B"]);
1463 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1464 /// assert_eq!(v, ["A", "", "B", ""]);
1466 /// let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
1467 /// assert_eq!(v, ["A", "B", "C", "D"]);
1469 #[stable(feature = "rust1", since = "1.0.0")]
1471 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1472 SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1475 /// An iterator over substrings of `self`, separated by characters
1476 /// matched by a pattern and yielded in reverse order.
1478 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1479 /// function or closure that determines if a character matches.
1481 /// [`char`]: prim@char
1482 /// [pattern]: self::pattern
1484 /// Equivalent to [`split`], except that the trailing substring is
1485 /// skipped if empty.
1487 /// [`split`]: str::split
1489 /// This method can be used for string data that is _terminated_,
1490 /// rather than _separated_ by a pattern.
1492 /// # Iterator behavior
1494 /// The returned iterator requires that the pattern supports a
1495 /// reverse search, and it will be double ended if a forward/reverse
1496 /// search yields the same elements.
1498 /// For iterating from the front, the [`split_terminator`] method can be
1501 /// [`split_terminator`]: str::split_terminator
1506 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1507 /// assert_eq!(v, ["B", "A"]);
1509 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1510 /// assert_eq!(v, ["", "B", "", "A"]);
1512 /// let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
1513 /// assert_eq!(v, ["D", "C", "B", "A"]);
1515 #[stable(feature = "rust1", since = "1.0.0")]
1517 pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1519 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1521 RSplitTerminator(self.split_terminator(pat).0)
1524 /// An iterator over substrings of the given string slice, separated by a
1525 /// pattern, restricted to returning at most `n` items.
1527 /// If `n` substrings are returned, the last substring (the `n`th substring)
1528 /// will contain the remainder of the string.
1530 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1531 /// function or closure that determines if a character matches.
1533 /// [`char`]: prim@char
1534 /// [pattern]: self::pattern
1536 /// # Iterator behavior
1538 /// The returned iterator will not be double ended, because it is
1539 /// not efficient to support.
1541 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1544 /// [`rsplitn`]: str::rsplitn
1548 /// Simple patterns:
1551 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1552 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1554 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1555 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1557 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1558 /// assert_eq!(v, ["abcXdef"]);
1560 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1561 /// assert_eq!(v, [""]);
1564 /// A more complex pattern, using a closure:
1567 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1568 /// assert_eq!(v, ["abc", "defXghi"]);
1570 #[stable(feature = "rust1", since = "1.0.0")]
1572 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1573 SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1576 /// An iterator over substrings of this string slice, separated by a
1577 /// pattern, starting from the end of the string, restricted to returning
1578 /// at most `n` items.
1580 /// If `n` substrings are returned, the last substring (the `n`th substring)
1581 /// will contain the remainder of the string.
1583 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1584 /// function or closure that determines if a character matches.
1586 /// [`char`]: prim@char
1587 /// [pattern]: self::pattern
1589 /// # Iterator behavior
1591 /// The returned iterator will not be double ended, because it is not
1592 /// efficient to support.
1594 /// For splitting from the front, the [`splitn`] method can be used.
1596 /// [`splitn`]: str::splitn
1600 /// Simple patterns:
1603 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1604 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1606 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1607 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1609 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1610 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1613 /// A more complex pattern, using a closure:
1616 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1617 /// assert_eq!(v, ["ghi", "abc1def"]);
1619 #[stable(feature = "rust1", since = "1.0.0")]
1621 pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1623 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1625 RSplitN(self.splitn(n, pat).0)
1628 /// Splits the string on the first occurrence of the specified delimiter and
1629 /// returns prefix before delimiter and suffix after delimiter.
1634 /// assert_eq!("cfg".split_once('='), None);
1635 /// assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
1636 /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1637 /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1639 #[stable(feature = "str_split_once", since = "1.52.0")]
1641 pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> {
1642 let (start, end) = delimiter.into_searcher(self).next_match()?;
1643 // SAFETY: `Searcher` is known to return valid indices.
1644 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1647 /// Splits the string on the last occurrence of the specified delimiter and
1648 /// returns prefix before delimiter and suffix after delimiter.
1653 /// assert_eq!("cfg".rsplit_once('='), None);
1654 /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
1655 /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1657 #[stable(feature = "str_split_once", since = "1.52.0")]
1659 pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
1661 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1663 let (start, end) = delimiter.into_searcher(self).next_match_back()?;
1664 // SAFETY: `Searcher` is known to return valid indices.
1665 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1668 /// An iterator over the disjoint matches of a pattern within the given string
1671 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1672 /// function or closure that determines if a character matches.
1674 /// [`char`]: prim@char
1675 /// [pattern]: self::pattern
1677 /// # Iterator behavior
1679 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1680 /// allows a reverse search and forward/reverse search yields the same
1681 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1683 /// If the pattern allows a reverse search but its results might differ
1684 /// from a forward search, the [`rmatches`] method can be used.
1686 /// [`rmatches`]: str::matches
1693 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1694 /// assert_eq!(v, ["abc", "abc", "abc"]);
1696 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1697 /// assert_eq!(v, ["1", "2", "3"]);
1699 #[stable(feature = "str_matches", since = "1.2.0")]
1701 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1702 Matches(MatchesInternal(pat.into_searcher(self)))
1705 /// An iterator over the disjoint matches of a pattern within this string slice,
1706 /// yielded in reverse order.
1708 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1709 /// function or closure that determines if a character matches.
1711 /// [`char`]: prim@char
1712 /// [pattern]: self::pattern
1714 /// # Iterator behavior
1716 /// The returned iterator requires that the pattern supports a reverse
1717 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1718 /// search yields the same elements.
1720 /// For iterating from the front, the [`matches`] method can be used.
1722 /// [`matches`]: str::matches
1729 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1730 /// assert_eq!(v, ["abc", "abc", "abc"]);
1732 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1733 /// assert_eq!(v, ["3", "2", "1"]);
1735 #[stable(feature = "str_matches", since = "1.2.0")]
1737 pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>
1739 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1741 RMatches(self.matches(pat).0)
1744 /// An iterator over the disjoint matches of a pattern within this string
1745 /// slice as well as the index that the match starts at.
1747 /// For matches of `pat` within `self` that overlap, only the indices
1748 /// corresponding to the first match are returned.
1750 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1751 /// function or closure that determines if a character matches.
1753 /// [`char`]: prim@char
1754 /// [pattern]: self::pattern
1756 /// # Iterator behavior
1758 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1759 /// allows a reverse search and forward/reverse search yields the same
1760 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1762 /// If the pattern allows a reverse search but its results might differ
1763 /// from a forward search, the [`rmatch_indices`] method can be used.
1765 /// [`rmatch_indices`]: str::rmatch_indices
1772 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1773 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1775 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1776 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1778 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1779 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1781 #[stable(feature = "str_match_indices", since = "1.5.0")]
1783 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1784 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1787 /// An iterator over the disjoint matches of a pattern within `self`,
1788 /// yielded in reverse order along with the index of the match.
1790 /// For matches of `pat` within `self` that overlap, only the indices
1791 /// corresponding to the last match are returned.
1793 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1794 /// function or closure that determines if a character matches.
1796 /// [`char`]: prim@char
1797 /// [pattern]: self::pattern
1799 /// # Iterator behavior
1801 /// The returned iterator requires that the pattern supports a reverse
1802 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1803 /// search yields the same elements.
1805 /// For iterating from the front, the [`match_indices`] method can be used.
1807 /// [`match_indices`]: str::match_indices
1814 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1815 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1817 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1818 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1820 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1821 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1823 #[stable(feature = "str_match_indices", since = "1.5.0")]
1825 pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>
1827 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1829 RMatchIndices(self.match_indices(pat).0)
1832 /// Returns a string slice with leading and trailing whitespace removed.
1834 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1835 /// Core Property `White_Space`, which includes newlines.
1842 /// let s = "\n Hello\tworld\t\n";
1844 /// assert_eq!("Hello\tworld", s.trim());
1847 #[must_use = "this returns the trimmed string as a slice, \
1848 without modifying the original"]
1849 #[stable(feature = "rust1", since = "1.0.0")]
1850 #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim")]
1851 pub fn trim(&self) -> &str {
1852 self.trim_matches(|c: char| c.is_whitespace())
1855 /// Returns a string slice with leading whitespace removed.
1857 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1858 /// Core Property `White_Space`, which includes newlines.
1860 /// # Text directionality
1862 /// A string is a sequence of bytes. `start` in this context means the first
1863 /// position of that byte string; for a left-to-right language like English or
1864 /// Russian, this will be left side, and for right-to-left languages like
1865 /// Arabic or Hebrew, this will be the right side.
1872 /// let s = "\n Hello\tworld\t\n";
1873 /// assert_eq!("Hello\tworld\t\n", s.trim_start());
1879 /// let s = " English ";
1880 /// assert!(Some('E') == s.trim_start().chars().next());
1882 /// let s = " עברית ";
1883 /// assert!(Some('ע') == s.trim_start().chars().next());
1886 #[must_use = "this returns the trimmed string as a new slice, \
1887 without modifying the original"]
1888 #[stable(feature = "trim_direction", since = "1.30.0")]
1889 #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim_start")]
1890 pub fn trim_start(&self) -> &str {
1891 self.trim_start_matches(|c: char| c.is_whitespace())
1894 /// Returns a string slice with trailing whitespace removed.
1896 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1897 /// Core Property `White_Space`, which includes newlines.
1899 /// # Text directionality
1901 /// A string is a sequence of bytes. `end` in this context means the last
1902 /// position of that byte string; for a left-to-right language like English or
1903 /// Russian, this will be right side, and for right-to-left languages like
1904 /// Arabic or Hebrew, this will be the left side.
1911 /// let s = "\n Hello\tworld\t\n";
1912 /// assert_eq!("\n Hello\tworld", s.trim_end());
1918 /// let s = " English ";
1919 /// assert!(Some('h') == s.trim_end().chars().rev().next());
1921 /// let s = " עברית ";
1922 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
1925 #[must_use = "this returns the trimmed string as a new slice, \
1926 without modifying the original"]
1927 #[stable(feature = "trim_direction", since = "1.30.0")]
1928 #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim_end")]
1929 pub fn trim_end(&self) -> &str {
1930 self.trim_end_matches(|c: char| c.is_whitespace())
1933 /// Returns a string slice with leading whitespace removed.
1935 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1936 /// Core Property `White_Space`.
1938 /// # Text directionality
1940 /// A string is a sequence of bytes. 'Left' in this context means the first
1941 /// position of that byte string; for a language like Arabic or Hebrew
1942 /// which are 'right to left' rather than 'left to right', this will be
1943 /// the _right_ side, not the left.
1950 /// let s = " Hello\tworld\t";
1952 /// assert_eq!("Hello\tworld\t", s.trim_left());
1958 /// let s = " English";
1959 /// assert!(Some('E') == s.trim_left().chars().next());
1961 /// let s = " עברית";
1962 /// assert!(Some('ע') == s.trim_left().chars().next());
1964 #[must_use = "this returns the trimmed string as a new slice, \
1965 without modifying the original"]
1967 #[stable(feature = "rust1", since = "1.0.0")]
1968 #[deprecated(since = "1.33.0", note = "superseded by `trim_start`", suggestion = "trim_start")]
1969 pub fn trim_left(&self) -> &str {
1973 /// Returns a string slice with trailing whitespace removed.
1975 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1976 /// Core Property `White_Space`.
1978 /// # Text directionality
1980 /// A string is a sequence of bytes. 'Right' in this context means the last
1981 /// position of that byte string; for a language like Arabic or Hebrew
1982 /// which are 'right to left' rather than 'left to right', this will be
1983 /// the _left_ side, not the right.
1990 /// let s = " Hello\tworld\t";
1992 /// assert_eq!(" Hello\tworld", s.trim_right());
1998 /// let s = "English ";
1999 /// assert!(Some('h') == s.trim_right().chars().rev().next());
2001 /// let s = "עברית ";
2002 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
2004 #[must_use = "this returns the trimmed string as a new slice, \
2005 without modifying the original"]
2007 #[stable(feature = "rust1", since = "1.0.0")]
2008 #[deprecated(since = "1.33.0", note = "superseded by `trim_end`", suggestion = "trim_end")]
2009 pub fn trim_right(&self) -> &str {
2013 /// Returns a string slice with all prefixes and suffixes that match a
2014 /// pattern repeatedly removed.
2016 /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
2017 /// or closure that determines if a character matches.
2019 /// [`char`]: prim@char
2020 /// [pattern]: self::pattern
2024 /// Simple patterns:
2027 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
2028 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
2030 /// let x: &[_] = &['1', '2'];
2031 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
2034 /// A more complex pattern, using a closure:
2037 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
2039 #[must_use = "this returns the trimmed string as a new slice, \
2040 without modifying the original"]
2041 #[stable(feature = "rust1", since = "1.0.0")]
2042 pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
2044 P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
2048 let mut matcher = pat.into_searcher(self);
2049 if let Some((a, b)) = matcher.next_reject() {
2051 j = b; // Remember earliest known match, correct it below if
2052 // last match is different
2054 if let Some((_, b)) = matcher.next_reject_back() {
2057 // SAFETY: `Searcher` is known to return valid indices.
2058 unsafe { self.get_unchecked(i..j) }
2061 /// Returns a string slice with all prefixes that match a pattern
2062 /// repeatedly removed.
2064 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2065 /// function or closure that determines if a character matches.
2067 /// [`char`]: prim@char
2068 /// [pattern]: self::pattern
2070 /// # Text directionality
2072 /// A string is a sequence of bytes. `start` in this context means the first
2073 /// position of that byte string; for a left-to-right language like English or
2074 /// Russian, this will be left side, and for right-to-left languages like
2075 /// Arabic or Hebrew, this will be the right side.
2082 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
2083 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
2085 /// let x: &[_] = &['1', '2'];
2086 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
2088 #[must_use = "this returns the trimmed string as a new slice, \
2089 without modifying the original"]
2090 #[stable(feature = "trim_direction", since = "1.30.0")]
2091 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2092 let mut i = self.len();
2093 let mut matcher = pat.into_searcher(self);
2094 if let Some((a, _)) = matcher.next_reject() {
2097 // SAFETY: `Searcher` is known to return valid indices.
2098 unsafe { self.get_unchecked(i..self.len()) }
2101 /// Returns a string slice with the prefix removed.
2103 /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped
2104 /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once.
2106 /// If the string does not start with `prefix`, returns `None`.
2108 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2109 /// function or closure that determines if a character matches.
2111 /// [`char`]: prim@char
2112 /// [pattern]: self::pattern
2117 /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2118 /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2119 /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2121 #[must_use = "this returns the remaining substring as a new slice, \
2122 without modifying the original"]
2123 #[stable(feature = "str_strip", since = "1.45.0")]
2124 pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> {
2125 prefix.strip_prefix_of(self)
2128 /// Returns a string slice with the suffix removed.
2130 /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2131 /// wrapped in `Some`. Unlike `trim_end_matches`, this method removes the suffix exactly once.
2133 /// If the string does not end with `suffix`, returns `None`.
2135 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2136 /// function or closure that determines if a character matches.
2138 /// [`char`]: prim@char
2139 /// [pattern]: self::pattern
2144 /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2145 /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2146 /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2148 #[must_use = "this returns the remaining substring as a new slice, \
2149 without modifying the original"]
2150 #[stable(feature = "str_strip", since = "1.45.0")]
2151 pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
2154 <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
2156 suffix.strip_suffix_of(self)
2159 /// Returns a string slice with all suffixes that match a pattern
2160 /// repeatedly removed.
2162 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2163 /// function or closure that determines if a character matches.
2165 /// [`char`]: prim@char
2166 /// [pattern]: self::pattern
2168 /// # Text directionality
2170 /// A string is a sequence of bytes. `end` in this context means the last
2171 /// position of that byte string; for a left-to-right language like English or
2172 /// Russian, this will be right side, and for right-to-left languages like
2173 /// Arabic or Hebrew, this will be the left side.
2177 /// Simple patterns:
2180 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2181 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2183 /// let x: &[_] = &['1', '2'];
2184 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2187 /// A more complex pattern, using a closure:
2190 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2192 #[must_use = "this returns the trimmed string as a new slice, \
2193 without modifying the original"]
2194 #[stable(feature = "trim_direction", since = "1.30.0")]
2195 pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
2197 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2200 let mut matcher = pat.into_searcher(self);
2201 if let Some((_, b)) = matcher.next_reject_back() {
2204 // SAFETY: `Searcher` is known to return valid indices.
2205 unsafe { self.get_unchecked(0..j) }
2208 /// Returns a string slice with all prefixes that match a pattern
2209 /// repeatedly removed.
2211 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2212 /// function or closure that determines if a character matches.
2214 /// [`char`]: prim@char
2215 /// [pattern]: self::pattern
2217 /// # Text directionality
2219 /// A string is a sequence of bytes. 'Left' in this context means the first
2220 /// position of that byte string; for a language like Arabic or Hebrew
2221 /// which are 'right to left' rather than 'left to right', this will be
2222 /// the _right_ side, not the left.
2229 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2230 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2232 /// let x: &[_] = &['1', '2'];
2233 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2235 #[stable(feature = "rust1", since = "1.0.0")]
2238 note = "superseded by `trim_start_matches`",
2239 suggestion = "trim_start_matches"
2241 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2242 self.trim_start_matches(pat)
2245 /// Returns a string slice with all suffixes that match a pattern
2246 /// repeatedly removed.
2248 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2249 /// function or closure that determines if a character matches.
2251 /// [`char`]: prim@char
2252 /// [pattern]: self::pattern
2254 /// # Text directionality
2256 /// A string is a sequence of bytes. 'Right' in this context means the last
2257 /// position of that byte string; for a language like Arabic or Hebrew
2258 /// which are 'right to left' rather than 'left to right', this will be
2259 /// the _left_ side, not the right.
2263 /// Simple patterns:
2266 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2267 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2269 /// let x: &[_] = &['1', '2'];
2270 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2273 /// A more complex pattern, using a closure:
2276 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2278 #[stable(feature = "rust1", since = "1.0.0")]
2281 note = "superseded by `trim_end_matches`",
2282 suggestion = "trim_end_matches"
2284 pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
2286 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2288 self.trim_end_matches(pat)
2291 /// Parses this string slice into another type.
2293 /// Because `parse` is so general, it can cause problems with type
2294 /// inference. As such, `parse` is one of the few times you'll see
2295 /// the syntax affectionately known as the 'turbofish': `::<>`. This
2296 /// helps the inference algorithm understand specifically which type
2297 /// you're trying to parse into.
2299 /// `parse` can parse into any type that implements the [`FromStr`] trait.
2304 /// Will return [`Err`] if it's not possible to parse this string slice into
2305 /// the desired type.
2307 /// [`Err`]: FromStr::Err
2314 /// let four: u32 = "4".parse().unwrap();
2316 /// assert_eq!(4, four);
2319 /// Using the 'turbofish' instead of annotating `four`:
2322 /// let four = "4".parse::<u32>();
2324 /// assert_eq!(Ok(4), four);
2327 /// Failing to parse:
2330 /// let nope = "j".parse::<u32>();
2332 /// assert!(nope.is_err());
2335 #[stable(feature = "rust1", since = "1.0.0")]
2336 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2337 FromStr::from_str(self)
2340 /// Checks if all characters in this string are within the ASCII range.
2345 /// let ascii = "hello!\n";
2346 /// let non_ascii = "Grüße, Jürgen ❤";
2348 /// assert!(ascii.is_ascii());
2349 /// assert!(!non_ascii.is_ascii());
2351 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2354 pub fn is_ascii(&self) -> bool {
2355 // We can treat each byte as character here: all multibyte characters
2356 // start with a byte that is not in the ASCII range, so we will stop
2358 self.as_bytes().is_ascii()
2361 /// Checks that two strings are an ASCII case-insensitive match.
2363 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2364 /// but without allocating and copying temporaries.
2369 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2370 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2371 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2373 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2376 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2377 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2380 /// Converts this string to its ASCII upper case equivalent in-place.
2382 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2383 /// but non-ASCII letters are unchanged.
2385 /// To return a new uppercased value without modifying the existing one, use
2386 /// [`to_ascii_uppercase()`].
2388 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2393 /// let mut s = String::from("Grüße, Jürgen ❤");
2395 /// s.make_ascii_uppercase();
2397 /// assert_eq!("GRüßE, JüRGEN ❤", s);
2399 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2401 pub fn make_ascii_uppercase(&mut self) {
2402 // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2403 let me = unsafe { self.as_bytes_mut() };
2404 me.make_ascii_uppercase()
2407 /// Converts this string to its ASCII lower case equivalent in-place.
2409 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2410 /// but non-ASCII letters are unchanged.
2412 /// To return a new lowercased value without modifying the existing one, use
2413 /// [`to_ascii_lowercase()`].
2415 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2420 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2422 /// s.make_ascii_lowercase();
2424 /// assert_eq!("grÜße, jÜrgen ❤", s);
2426 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2428 pub fn make_ascii_lowercase(&mut self) {
2429 // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2430 let me = unsafe { self.as_bytes_mut() };
2431 me.make_ascii_lowercase()
2434 /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
2436 /// Note: only extended grapheme codepoints that begin the string will be
2444 /// for c in "❤\n!".escape_debug() {
2450 /// Using `println!` directly:
2453 /// println!("{}", "❤\n!".escape_debug());
2457 /// Both are equivalent to:
2460 /// println!("❤\\n!");
2463 /// Using `to_string`:
2466 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
2468 #[must_use = "this returns the escaped string as an iterator, \
2469 without modifying the original"]
2470 #[stable(feature = "str_escape", since = "1.34.0")]
2471 pub fn escape_debug(&self) -> EscapeDebug<'_> {
2472 let mut chars = self.chars();
2476 .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL))
2479 .chain(chars.flat_map(CharEscapeDebugContinue)),
2483 /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
2490 /// for c in "❤\n!".escape_default() {
2496 /// Using `println!` directly:
2499 /// println!("{}", "❤\n!".escape_default());
2503 /// Both are equivalent to:
2506 /// println!("\\u{{2764}}\\n!");
2509 /// Using `to_string`:
2512 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
2514 #[must_use = "this returns the escaped string as an iterator, \
2515 without modifying the original"]
2516 #[stable(feature = "str_escape", since = "1.34.0")]
2517 pub fn escape_default(&self) -> EscapeDefault<'_> {
2518 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
2521 /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
2528 /// for c in "❤\n!".escape_unicode() {
2534 /// Using `println!` directly:
2537 /// println!("{}", "❤\n!".escape_unicode());
2541 /// Both are equivalent to:
2544 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
2547 /// Using `to_string`:
2550 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
2552 #[must_use = "this returns the escaped string as an iterator, \
2553 without modifying the original"]
2554 #[stable(feature = "str_escape", since = "1.34.0")]
2555 pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
2556 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
2560 #[stable(feature = "rust1", since = "1.0.0")]
2561 impl AsRef<[u8]> for str {
2563 fn as_ref(&self) -> &[u8] {
2568 #[stable(feature = "rust1", since = "1.0.0")]
2569 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
2570 impl const Default for &str {
2571 /// Creates an empty str
2573 fn default() -> Self {
2578 #[stable(feature = "default_mut_str", since = "1.28.0")]
2579 impl Default for &mut str {
2580 /// Creates an empty mutable str
2582 fn default() -> Self {
2583 // SAFETY: The empty string is valid UTF-8.
2584 unsafe { from_utf8_unchecked_mut(&mut []) }
2589 /// A nameable, cloneable fn type
2591 struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
2593 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
2598 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
2599 c.escape_debug_ext(EscapeDebugExtArgs {
2600 escape_grapheme_extended: false,
2601 escape_single_quote: true,
2602 escape_double_quote: true
2607 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
2611 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
2616 struct IsWhitespace impl Fn = |c: char| -> bool {
2621 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
2622 byte.is_ascii_whitespace()
2626 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
2631 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
2636 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
2638 unsafe { from_utf8_unchecked(bytes) }
2642 #[stable(feature = "rust1", since = "1.0.0")]
2643 #[cfg(not(bootstrap))]
2644 impl !crate::error::Error for &str {}