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")]
15 use self::pattern
::Pattern
;
16 use self::pattern
::{DoubleEndedSearcher, ReverseSearcher, Searcher}
;
20 use crate::slice
::{self, SliceIndex}
;
24 #[unstable(feature = "str_internals", issue = "none")]
25 #[allow(missing_docs)]
28 #[stable(feature = "rust1", since = "1.0.0")]
29 pub use converts
::{from_utf8, from_utf8_unchecked}
;
31 #[stable(feature = "str_mut_extras", since = "1.20.0")]
32 pub use converts
::{from_utf8_mut, from_utf8_unchecked_mut}
;
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use error
::{ParseBoolError, Utf8Error}
;
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use traits
::FromStr
;
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub use iter
::{Bytes, CharIndices, Chars, Lines, SplitWhitespace}
;
43 #[stable(feature = "rust1", since = "1.0.0")]
45 pub use iter
::LinesAny
;
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub use iter
::{RSplit, RSplitTerminator, Split, SplitTerminator}
;
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub use iter
::{RSplitN, SplitN}
;
53 #[stable(feature = "str_matches", since = "1.2.0")]
54 pub use iter
::{Matches, RMatches}
;
56 #[stable(feature = "str_match_indices", since = "1.5.0")]
57 pub use iter
::{MatchIndices, RMatchIndices}
;
59 #[stable(feature = "encode_utf16", since = "1.8.0")]
60 pub use iter
::EncodeUtf16
;
62 #[stable(feature = "str_escape", since = "1.34.0")]
63 pub use iter
::{EscapeDebug, EscapeDefault, EscapeUnicode}
;
65 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
66 pub use iter
::SplitAsciiWhitespace
;
68 #[unstable(feature = "split_inclusive", issue = "72360")]
69 use iter
::SplitInclusive
;
71 #[unstable(feature = "str_internals", issue = "none")]
72 pub use validations
::next_code_point
;
74 use iter
::MatchIndicesInternal
;
75 use iter
::SplitInternal
;
76 use iter
::{MatchesInternal, SplitNInternal}
;
78 use validations
::truncate_to_char_boundary
;
83 fn slice_error_fail(s
: &str, begin
: usize, end
: usize) -> ! {
84 const MAX_DISPLAY_LENGTH
: usize = 256;
85 let (truncated
, s_trunc
) = truncate_to_char_boundary(s
, MAX_DISPLAY_LENGTH
);
86 let ellipsis
= if truncated { "[...]" }
else { "" }
;
89 if begin
> s
.len() || end
> s
.len() {
90 let oob_index
= if begin
> s
.len() { begin }
else { end }
;
91 panic
!("byte index {} is out of bounds of `{}`{}", oob_index
, s_trunc
, ellipsis
);
97 "begin <= end ({} <= {}) when slicing `{}`{}",
104 // 3. character boundary
105 let index
= if !s
.is_char_boundary(begin
) { begin }
else { end }
;
106 // find the character
107 let mut char_start
= index
;
108 while !s
.is_char_boundary(char_start
) {
111 // `char_start` must be less than len and a char boundary
112 let ch
= s
[char_start
..].chars().next().unwrap();
113 let char_range
= char_start
..char_start
+ ch
.len_utf8();
115 "byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
116 index
, ch
, char_range
, s_trunc
, ellipsis
123 /// Returns the length of `self`.
125 /// This length is in bytes, not [`char`]s or graphemes. In other words,
126 /// it may not be what a human considers the length of the string.
128 /// [`char`]: prim@char
135 /// let len = "foo".len();
136 /// assert_eq!(3, len);
138 /// assert_eq!("ƒoo".len(), 4); // fancy f!
139 /// assert_eq!("ƒoo".chars().count(), 3);
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[rustc_const_stable(feature = "const_str_len", since = "1.32.0")]
144 pub const fn len(&self) -> usize {
145 self.as_bytes().len()
148 /// Returns `true` if `self` has a length of zero bytes.
156 /// assert!(s.is_empty());
158 /// let s = "not empty";
159 /// assert!(!s.is_empty());
162 #[stable(feature = "rust1", since = "1.0.0")]
163 #[rustc_const_stable(feature = "const_str_is_empty", since = "1.32.0")]
164 pub const fn is_empty(&self) -> bool
{
168 /// Checks that `index`-th byte is the first byte in a UTF-8 code point
169 /// sequence or the end of the string.
171 /// The start and end of the string (when `index == self.len()`) are
172 /// considered to be boundaries.
174 /// Returns `false` if `index` is greater than `self.len()`.
179 /// let s = "Löwe 老虎 Léopard";
180 /// assert!(s.is_char_boundary(0));
182 /// assert!(s.is_char_boundary(6));
183 /// assert!(s.is_char_boundary(s.len()));
185 /// // second byte of `ö`
186 /// assert!(!s.is_char_boundary(2));
188 /// // third byte of `老`
189 /// assert!(!s.is_char_boundary(8));
191 #[stable(feature = "is_char_boundary", since = "1.9.0")]
193 pub fn is_char_boundary(&self, index
: usize) -> bool
{
194 // 0 and len are always ok.
195 // Test for 0 explicitly so that it can optimize out the check
196 // easily and skip reading string data for that case.
197 if index
== 0 || index
== self.len() {
200 match self.as_bytes().get(index
) {
202 // This is bit magic equivalent to: b < 128 || b >= 192
203 Some(&b
) => (b
as i8) >= -0x40,
207 /// Converts a string slice to a byte slice. To convert the byte slice back
208 /// into a string slice, use the [`from_utf8`] function.
215 /// let bytes = "bors".as_bytes();
216 /// assert_eq!(b"bors", bytes);
218 #[stable(feature = "rust1", since = "1.0.0")]
219 #[rustc_const_stable(feature = "str_as_bytes", since = "1.32.0")]
221 #[allow(unused_attributes)]
222 #[cfg_attr(not(bootstrap), rustc_allow_const_fn_unstable(const_fn_transmute))]
223 #[cfg_attr(bootstrap, allow_internal_unstable(const_fn_transmute))]
224 pub const fn as_bytes(&self) -> &[u8] {
225 // SAFETY: const sound because we transmute two types with the same layout
226 unsafe { mem::transmute(self) }
229 /// Converts a mutable string slice to a mutable byte slice.
233 /// The caller must ensure that the content of the slice is valid UTF-8
234 /// before the borrow ends and the underlying `str` is used.
236 /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
243 /// let mut s = String::from("Hello");
244 /// let bytes = unsafe { s.as_bytes_mut() };
246 /// assert_eq!(b"Hello", bytes);
252 /// let mut s = String::from("🗻∈🌏");
255 /// let bytes = s.as_bytes_mut();
263 /// assert_eq!("🍔∈🌏", s);
265 #[stable(feature = "str_mut_extras", since = "1.20.0")]
267 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
268 // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
269 // has the same layout as `&[u8]` (only libstd can make this guarantee).
270 // The pointer dereference is safe since it comes from a mutable reference which
271 // is guaranteed to be valid for writes.
272 unsafe { &mut *(self as *mut str as *mut [u8]) }
275 /// Converts a string slice to a raw pointer.
277 /// As string slices are a slice of bytes, the raw pointer points to a
278 /// [`u8`]. This pointer will be pointing to the first byte of the string
281 /// The caller must ensure that the returned pointer is never written to.
282 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
284 /// [`as_mut_ptr`]: str::as_mut_ptr
292 /// let ptr = s.as_ptr();
294 #[stable(feature = "rust1", since = "1.0.0")]
295 #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
297 pub const fn as_ptr(&self) -> *const u8 {
298 self as *const str as *const u8
301 /// Converts a mutable string slice to a raw pointer.
303 /// As string slices are a slice of bytes, the raw pointer points to a
304 /// [`u8`]. This pointer will be pointing to the first byte of the string
307 /// It is your responsibility to make sure that the string slice only gets
308 /// modified in a way that it remains valid UTF-8.
309 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
311 pub fn as_mut_ptr(&mut self) -> *mut u8 {
312 self as *mut str as *mut u8
315 /// Returns a subslice of `str`.
317 /// This is the non-panicking alternative to indexing the `str`. Returns
318 /// [`None`] whenever equivalent indexing operation would panic.
323 /// let v = String::from("🗻∈🌏");
325 /// assert_eq!(Some("🗻"), v.get(0..4));
327 /// // indices not on UTF-8 sequence boundaries
328 /// assert!(v.get(1..).is_none());
329 /// assert!(v.get(..8).is_none());
332 /// assert!(v.get(..42).is_none());
334 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
336 pub fn get
<I
: SliceIndex
<str>>(&self, i
: I
) -> Option
<&I
::Output
> {
340 /// Returns a mutable subslice of `str`.
342 /// This is the non-panicking alternative to indexing the `str`. Returns
343 /// [`None`] whenever equivalent indexing operation would panic.
348 /// let mut v = String::from("hello");
349 /// // correct length
350 /// assert!(v.get_mut(0..5).is_some());
352 /// assert!(v.get_mut(..42).is_none());
353 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
355 /// assert_eq!("hello", v);
357 /// let s = v.get_mut(0..2);
358 /// let s = s.map(|s| {
359 /// s.make_ascii_uppercase();
362 /// assert_eq!(Some("HE"), s);
364 /// assert_eq!("HEllo", v);
366 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
368 pub fn get_mut
<I
: SliceIndex
<str>>(&mut self, i
: I
) -> Option
<&mut I
::Output
> {
372 /// Returns an unchecked subslice of `str`.
374 /// This is the unchecked alternative to indexing the `str`.
378 /// Callers of this function are responsible that these preconditions are
381 /// * The starting index must not exceed the ending index;
382 /// * Indexes must be within bounds of the original slice;
383 /// * Indexes must lie on UTF-8 sequence boundaries.
385 /// Failing that, the returned string slice may reference invalid memory or
386 /// violate the invariants communicated by the `str` type.
393 /// assert_eq!("🗻", v.get_unchecked(0..4));
394 /// assert_eq!("∈", v.get_unchecked(4..7));
395 /// assert_eq!("🌏", v.get_unchecked(7..11));
398 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
400 pub unsafe fn get_unchecked
<I
: SliceIndex
<str>>(&self, i
: I
) -> &I
::Output
{
401 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
402 // the slice is dereferencable because `self` is a safe reference.
403 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
404 unsafe { &*i.get_unchecked(self) }
407 /// Returns a mutable, unchecked subslice of `str`.
409 /// This is the unchecked alternative to indexing the `str`.
413 /// Callers of this function are responsible that these preconditions are
416 /// * The starting index must not exceed the ending index;
417 /// * Indexes must be within bounds of the original slice;
418 /// * Indexes must lie on UTF-8 sequence boundaries.
420 /// Failing that, the returned string slice may reference invalid memory or
421 /// violate the invariants communicated by the `str` type.
426 /// let mut v = String::from("🗻∈🌏");
428 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
429 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
430 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
433 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
435 pub unsafe fn get_unchecked_mut
<I
: SliceIndex
<str>>(&mut self, i
: I
) -> &mut I
::Output
{
436 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
437 // the slice is dereferencable because `self` is a safe reference.
438 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
439 unsafe { &mut *i.get_unchecked_mut(self) }
442 /// Creates a string slice from another string slice, bypassing safety
445 /// This is generally not recommended, use with caution! For a safe
446 /// alternative see [`str`] and [`Index`].
448 /// [`Index`]: crate::ops::Index
450 /// This new slice goes from `begin` to `end`, including `begin` but
453 /// To get a mutable string slice instead, see the
454 /// [`slice_mut_unchecked`] method.
456 /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
460 /// Callers of this function are responsible that three preconditions are
463 /// * `begin` must not exceed `end`.
464 /// * `begin` and `end` must be byte positions within the string slice.
465 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
472 /// let s = "Löwe 老虎 Léopard";
475 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
478 /// let s = "Hello, world!";
481 /// assert_eq!("world", s.slice_unchecked(7, 12));
484 #[stable(feature = "rust1", since = "1.0.0")]
485 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
487 pub unsafe fn slice_unchecked(&self, begin
: usize, end
: usize) -> &str {
488 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
489 // the slice is dereferencable because `self` is a safe reference.
490 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
491 unsafe { &*(begin..end).get_unchecked(self) }
494 /// Creates a string slice from another string slice, bypassing safety
496 /// This is generally not recommended, use with caution! For a safe
497 /// alternative see [`str`] and [`IndexMut`].
499 /// [`IndexMut`]: crate::ops::IndexMut
501 /// This new slice goes from `begin` to `end`, including `begin` but
504 /// To get an immutable string slice instead, see the
505 /// [`slice_unchecked`] method.
507 /// [`slice_unchecked`]: str::slice_unchecked
511 /// Callers of this function are responsible that three preconditions are
514 /// * `begin` must not exceed `end`.
515 /// * `begin` and `end` must be byte positions within the string slice.
516 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
517 #[stable(feature = "str_slice_mut", since = "1.5.0")]
518 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
520 pub unsafe fn slice_mut_unchecked(&mut self, begin
: usize, end
: usize) -> &mut str {
521 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
522 // the slice is dereferencable because `self` is a safe reference.
523 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
524 unsafe { &mut *(begin..end).get_unchecked_mut(self) }
527 /// Divide one string slice into two at an index.
529 /// The argument, `mid`, should be a byte offset from the start of the
530 /// string. It must also be on the boundary of a UTF-8 code point.
532 /// The two slices returned go from the start of the string slice to `mid`,
533 /// and from `mid` to the end of the string slice.
535 /// To get mutable string slices instead, see the [`split_at_mut`]
538 /// [`split_at_mut`]: str::split_at_mut
542 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
543 /// past the end of the last code point of the string slice.
550 /// let s = "Per Martin-Löf";
552 /// let (first, last) = s.split_at(3);
554 /// assert_eq!("Per", first);
555 /// assert_eq!(" Martin-Löf", last);
558 #[stable(feature = "str_split_at", since = "1.4.0")]
559 pub fn split_at(&self, mid
: usize) -> (&str, &str) {
560 // is_char_boundary checks that the index is in [0, .len()]
561 if self.is_char_boundary(mid
) {
562 // SAFETY: just checked that `mid` is on a char boundary.
563 unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) }
565 slice_error_fail(self, 0, mid
)
569 /// Divide one mutable string slice into two at an index.
571 /// The argument, `mid`, should be a byte offset from the start of the
572 /// string. It must also be on the boundary of a UTF-8 code point.
574 /// The two slices returned go from the start of the string slice to `mid`,
575 /// and from `mid` to the end of the string slice.
577 /// To get immutable string slices instead, see the [`split_at`] method.
579 /// [`split_at`]: str::split_at
583 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
584 /// past the end of the last code point of the string slice.
591 /// let mut s = "Per Martin-Löf".to_string();
593 /// let (first, last) = s.split_at_mut(3);
594 /// first.make_ascii_uppercase();
595 /// assert_eq!("PER", first);
596 /// assert_eq!(" Martin-Löf", last);
598 /// assert_eq!("PER Martin-Löf", s);
601 #[stable(feature = "str_split_at", since = "1.4.0")]
602 pub fn split_at_mut(&mut self, mid
: usize) -> (&mut str, &mut str) {
603 // is_char_boundary checks that the index is in [0, .len()]
604 if self.is_char_boundary(mid
) {
605 let len
= self.len();
606 let ptr
= self.as_mut_ptr();
607 // SAFETY: just checked that `mid` is on a char boundary.
610 from_utf8_unchecked_mut(slice
::from_raw_parts_mut(ptr
, mid
)),
611 from_utf8_unchecked_mut(slice
::from_raw_parts_mut(ptr
.add(mid
), len
- mid
)),
615 slice_error_fail(self, 0, mid
)
619 /// Returns an iterator over the [`char`]s of a string slice.
621 /// As a string slice consists of valid UTF-8, we can iterate through a
622 /// string slice by [`char`]. This method returns such an iterator.
624 /// It's important to remember that [`char`] represents a Unicode Scalar
625 /// Value, and may not match your idea of what a 'character' is. Iteration
626 /// over grapheme clusters may be what you actually want. This functionality
627 /// is not provided by Rust's standard library, check crates.io instead.
634 /// let word = "goodbye";
636 /// let count = word.chars().count();
637 /// assert_eq!(7, count);
639 /// let mut chars = word.chars();
641 /// assert_eq!(Some('g'), chars.next());
642 /// assert_eq!(Some('o'), chars.next());
643 /// assert_eq!(Some('o'), chars.next());
644 /// assert_eq!(Some('d'), chars.next());
645 /// assert_eq!(Some('b'), chars.next());
646 /// assert_eq!(Some('y'), chars.next());
647 /// assert_eq!(Some('e'), chars.next());
649 /// assert_eq!(None, chars.next());
652 /// Remember, [`char`]s may not match your intuition about characters:
654 /// [`char`]: prim@char
659 /// let mut chars = y.chars();
661 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
662 /// assert_eq!(Some('\u{0306}'), chars.next());
664 /// assert_eq!(None, chars.next());
666 #[stable(feature = "rust1", since = "1.0.0")]
668 pub fn chars(&self) -> Chars
<'_
> {
669 Chars { iter: self.as_bytes().iter() }
672 /// Returns an iterator over the [`char`]s of a string slice, and their
675 /// As a string slice consists of valid UTF-8, we can iterate through a
676 /// string slice by [`char`]. This method returns an iterator of both
677 /// these [`char`]s, as well as their byte positions.
679 /// The iterator yields tuples. The position is first, the [`char`] is
687 /// let word = "goodbye";
689 /// let count = word.char_indices().count();
690 /// assert_eq!(7, count);
692 /// let mut char_indices = word.char_indices();
694 /// assert_eq!(Some((0, 'g')), char_indices.next());
695 /// assert_eq!(Some((1, 'o')), char_indices.next());
696 /// assert_eq!(Some((2, 'o')), char_indices.next());
697 /// assert_eq!(Some((3, 'd')), char_indices.next());
698 /// assert_eq!(Some((4, 'b')), char_indices.next());
699 /// assert_eq!(Some((5, 'y')), char_indices.next());
700 /// assert_eq!(Some((6, 'e')), char_indices.next());
702 /// assert_eq!(None, char_indices.next());
705 /// Remember, [`char`]s may not match your intuition about characters:
707 /// [`char`]: prim@char
710 /// let yes = "y̆es";
712 /// let mut char_indices = yes.char_indices();
714 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
715 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
717 /// // note the 3 here - the last character took up two bytes
718 /// assert_eq!(Some((3, 'e')), char_indices.next());
719 /// assert_eq!(Some((4, 's')), char_indices.next());
721 /// assert_eq!(None, char_indices.next());
723 #[stable(feature = "rust1", since = "1.0.0")]
725 pub fn char_indices(&self) -> CharIndices
<'_
> {
726 CharIndices { front_offset: 0, iter: self.chars() }
729 /// An iterator over the bytes of a string slice.
731 /// As a string slice consists of a sequence of bytes, we can iterate
732 /// through a string slice by byte. This method returns such an iterator.
739 /// let mut bytes = "bors".bytes();
741 /// assert_eq!(Some(b'b'), bytes.next());
742 /// assert_eq!(Some(b'o'), bytes.next());
743 /// assert_eq!(Some(b'r'), bytes.next());
744 /// assert_eq!(Some(b's'), bytes.next());
746 /// assert_eq!(None, bytes.next());
748 #[stable(feature = "rust1", since = "1.0.0")]
750 pub fn bytes(&self) -> Bytes
<'_
> {
751 Bytes(self.as_bytes().iter().copied())
754 /// Splits a string slice by whitespace.
756 /// The iterator returned will return string slices that are sub-slices of
757 /// the original string slice, separated by any amount of whitespace.
759 /// 'Whitespace' is defined according to the terms of the Unicode Derived
760 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
761 /// instead, use [`split_ascii_whitespace`].
763 /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
770 /// let mut iter = "A few words".split_whitespace();
772 /// assert_eq!(Some("A"), iter.next());
773 /// assert_eq!(Some("few"), iter.next());
774 /// assert_eq!(Some("words"), iter.next());
776 /// assert_eq!(None, iter.next());
779 /// All kinds of whitespace are considered:
782 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
783 /// assert_eq!(Some("Mary"), iter.next());
784 /// assert_eq!(Some("had"), iter.next());
785 /// assert_eq!(Some("a"), iter.next());
786 /// assert_eq!(Some("little"), iter.next());
787 /// assert_eq!(Some("lamb"), iter.next());
789 /// assert_eq!(None, iter.next());
791 #[stable(feature = "split_whitespace", since = "1.1.0")]
793 pub fn split_whitespace(&self) -> SplitWhitespace
<'_
> {
794 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
797 /// Splits a string slice by ASCII whitespace.
799 /// The iterator returned will return string slices that are sub-slices of
800 /// the original string slice, separated by any amount of ASCII whitespace.
802 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
804 /// [`split_whitespace`]: str::split_whitespace
811 /// let mut iter = "A few words".split_ascii_whitespace();
813 /// assert_eq!(Some("A"), iter.next());
814 /// assert_eq!(Some("few"), iter.next());
815 /// assert_eq!(Some("words"), iter.next());
817 /// assert_eq!(None, iter.next());
820 /// All kinds of ASCII whitespace are considered:
823 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
824 /// assert_eq!(Some("Mary"), iter.next());
825 /// assert_eq!(Some("had"), iter.next());
826 /// assert_eq!(Some("a"), iter.next());
827 /// assert_eq!(Some("little"), iter.next());
828 /// assert_eq!(Some("lamb"), iter.next());
830 /// assert_eq!(None, iter.next());
832 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
834 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace
<'_
> {
836 self.as_bytes().split(IsAsciiWhitespace
).filter(BytesIsNotEmpty
).map(UnsafeBytesToStr
);
837 SplitAsciiWhitespace { inner }
840 /// An iterator over the lines of a string, as string slices.
842 /// Lines are ended with either a newline (`\n`) or a carriage return with
843 /// a line feed (`\r\n`).
845 /// The final line ending is optional. A string that ends with a final line
846 /// ending will return the same lines as an otherwise identical string
847 /// without a final line ending.
854 /// let text = "foo\r\nbar\n\nbaz\n";
855 /// let mut lines = text.lines();
857 /// assert_eq!(Some("foo"), lines.next());
858 /// assert_eq!(Some("bar"), lines.next());
859 /// assert_eq!(Some(""), lines.next());
860 /// assert_eq!(Some("baz"), lines.next());
862 /// assert_eq!(None, lines.next());
865 /// The final line ending isn't required:
868 /// let text = "foo\nbar\n\r\nbaz";
869 /// let mut lines = text.lines();
871 /// assert_eq!(Some("foo"), lines.next());
872 /// assert_eq!(Some("bar"), lines.next());
873 /// assert_eq!(Some(""), lines.next());
874 /// assert_eq!(Some("baz"), lines.next());
876 /// assert_eq!(None, lines.next());
878 #[stable(feature = "rust1", since = "1.0.0")]
880 pub fn lines(&self) -> Lines
<'_
> {
881 Lines(self.split_terminator('
\n'
).map(LinesAnyMap
))
884 /// An iterator over the lines of a string.
885 #[stable(feature = "rust1", since = "1.0.0")]
886 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
889 pub fn lines_any(&self) -> LinesAny
<'_
> {
890 LinesAny(self.lines())
893 /// Returns an iterator of `u16` over the string encoded as UTF-16.
900 /// let text = "Zażółć gęślą jaźń";
902 /// let utf8_len = text.len();
903 /// let utf16_len = text.encode_utf16().count();
905 /// assert!(utf16_len <= utf8_len);
907 #[stable(feature = "encode_utf16", since = "1.8.0")]
908 pub fn encode_utf16(&self) -> EncodeUtf16
<'_
> {
909 EncodeUtf16 { chars: self.chars(), extra: 0 }
912 /// Returns `true` if the given pattern matches a sub-slice of
913 /// this string slice.
915 /// Returns `false` if it does not.
917 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
918 /// function or closure that determines if a character matches.
920 /// [`char`]: prim@char
921 /// [pattern]: self::pattern
928 /// let bananas = "bananas";
930 /// assert!(bananas.contains("nana"));
931 /// assert!(!bananas.contains("apples"));
933 #[stable(feature = "rust1", since = "1.0.0")]
935 pub fn contains
<'a
, P
: Pattern
<'a
>>(&'a
self, pat
: P
) -> bool
{
936 pat
.is_contained_in(self)
939 /// Returns `true` if the given pattern matches a prefix of this
942 /// Returns `false` if it does not.
944 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
945 /// function or closure that determines if a character matches.
947 /// [`char`]: prim@char
948 /// [pattern]: self::pattern
955 /// let bananas = "bananas";
957 /// assert!(bananas.starts_with("bana"));
958 /// assert!(!bananas.starts_with("nana"));
960 #[stable(feature = "rust1", since = "1.0.0")]
961 pub fn starts_with
<'a
, P
: Pattern
<'a
>>(&'a
self, pat
: P
) -> bool
{
962 pat
.is_prefix_of(self)
965 /// Returns `true` if the given pattern matches a suffix of this
968 /// Returns `false` if it does not.
970 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
971 /// function or closure that determines if a character matches.
973 /// [`char`]: prim@char
974 /// [pattern]: self::pattern
981 /// let bananas = "bananas";
983 /// assert!(bananas.ends_with("anas"));
984 /// assert!(!bananas.ends_with("nana"));
986 #[stable(feature = "rust1", since = "1.0.0")]
987 pub fn ends_with
<'a
, P
>(&'a
self, pat
: P
) -> bool
989 P
: Pattern
<'a
, Searcher
: ReverseSearcher
<'a
>>,
991 pat
.is_suffix_of(self)
994 /// Returns the byte index of the first character of this string slice that
995 /// matches the pattern.
997 /// Returns [`None`] if the pattern doesn't match.
999 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1000 /// function or closure that determines if a character matches.
1002 /// [`char`]: prim@char
1003 /// [pattern]: self::pattern
1007 /// Simple patterns:
1010 /// let s = "Löwe 老虎 Léopard Gepardi";
1012 /// assert_eq!(s.find('L'), Some(0));
1013 /// assert_eq!(s.find('é'), Some(14));
1014 /// assert_eq!(s.find("pard"), Some(17));
1017 /// More complex patterns using point-free style and closures:
1020 /// let s = "Löwe 老虎 Léopard";
1022 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1023 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1024 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1025 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1028 /// Not finding the pattern:
1031 /// let s = "Löwe 老虎 Léopard";
1032 /// let x: &[_] = &['1', '2'];
1034 /// assert_eq!(s.find(x), None);
1036 #[stable(feature = "rust1", since = "1.0.0")]
1038 pub fn find
<'a
, P
: Pattern
<'a
>>(&'a
self, pat
: P
) -> Option
<usize> {
1039 pat
.into_searcher(self).next_match().map(|(i
, _
)| i
)
1042 /// Returns the byte index for the first character of the rightmost match of the pattern in
1043 /// this string slice.
1045 /// Returns [`None`] if the pattern doesn't match.
1047 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1048 /// function or closure that determines if a character matches.
1050 /// [`char`]: prim@char
1051 /// [pattern]: self::pattern
1055 /// Simple patterns:
1058 /// let s = "Löwe 老虎 Léopard Gepardi";
1060 /// assert_eq!(s.rfind('L'), Some(13));
1061 /// assert_eq!(s.rfind('é'), Some(14));
1062 /// assert_eq!(s.rfind("pard"), Some(24));
1065 /// More complex patterns with closures:
1068 /// let s = "Löwe 老虎 Léopard";
1070 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1071 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1074 /// Not finding the pattern:
1077 /// let s = "Löwe 老虎 Léopard";
1078 /// let x: &[_] = &['1', '2'];
1080 /// assert_eq!(s.rfind(x), None);
1082 #[stable(feature = "rust1", since = "1.0.0")]
1084 pub fn rfind
<'a
, P
>(&'a
self, pat
: P
) -> Option
<usize>
1086 P
: Pattern
<'a
, Searcher
: ReverseSearcher
<'a
>>,
1088 pat
.into_searcher(self).next_match_back().map(|(i
, _
)| i
)
1091 /// An iterator over substrings of this string slice, separated by
1092 /// characters matched by a pattern.
1094 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1095 /// function or closure that determines if a character matches.
1097 /// [`char`]: prim@char
1098 /// [pattern]: self::pattern
1100 /// # Iterator behavior
1102 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1103 /// allows a reverse search and forward/reverse search yields the same
1104 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1106 /// If the pattern allows a reverse search but its results might differ
1107 /// from a forward search, the [`rsplit`] method can be used.
1109 /// [`rsplit`]: str::rsplit
1113 /// Simple patterns:
1116 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1117 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1119 /// let v: Vec<&str> = "".split('X').collect();
1120 /// assert_eq!(v, [""]);
1122 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1123 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1125 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1126 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1128 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1129 /// assert_eq!(v, ["abc", "def", "ghi"]);
1131 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1132 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1135 /// A more complex pattern, using a closure:
1138 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1139 /// assert_eq!(v, ["abc", "def", "ghi"]);
1142 /// If a string contains multiple contiguous separators, you will end up
1143 /// with empty strings in the output:
1146 /// let x = "||||a||b|c".to_string();
1147 /// let d: Vec<_> = x.split('|').collect();
1149 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1152 /// Contiguous separators are separated by the empty string.
1155 /// let x = "(///)".to_string();
1156 /// let d: Vec<_> = x.split('/').collect();
1158 /// assert_eq!(d, &["(", "", "", ")"]);
1161 /// Separators at the start or end of a string are neighbored
1162 /// by empty strings.
1165 /// let d: Vec<_> = "010".split("0").collect();
1166 /// assert_eq!(d, &["", "1", ""]);
1169 /// When the empty string is used as a separator, it separates
1170 /// every character in the string, along with the beginning
1171 /// and end of the string.
1174 /// let f: Vec<_> = "rust".split("").collect();
1175 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1178 /// Contiguous separators can lead to possibly surprising behavior
1179 /// when whitespace is used as the separator. This code is correct:
1182 /// let x = " a b c".to_string();
1183 /// let d: Vec<_> = x.split(' ').collect();
1185 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1188 /// It does _not_ give you:
1191 /// assert_eq!(d, &["a", "b", "c"]);
1194 /// Use [`split_whitespace`] for this behavior.
1196 /// [`split_whitespace`]: str::split_whitespace
1197 #[stable(feature = "rust1", since = "1.0.0")]
1199 pub fn split
<'a
, P
: Pattern
<'a
>>(&'a
self, pat
: P
) -> Split
<'a
, P
> {
1200 Split(SplitInternal
{
1203 matcher
: pat
.into_searcher(self),
1204 allow_trailing_empty
: true,
1209 /// An iterator over substrings of this string slice, separated by
1210 /// characters matched by a pattern. Differs from the iterator produced by
1211 /// `split` in that `split_inclusive` leaves the matched part as the
1212 /// terminator of the substring.
1214 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1215 /// function or closure that determines if a character matches.
1217 /// [`char`]: prim@char
1218 /// [pattern]: self::pattern
1223 /// #![feature(split_inclusive)]
1224 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1225 /// .split_inclusive('\n').collect();
1226 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1229 /// If the last element of the string is matched,
1230 /// that element will be considered the terminator of the preceding substring.
1231 /// That substring will be the last item returned by the iterator.
1234 /// #![feature(split_inclusive)]
1235 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1236 /// .split_inclusive('\n').collect();
1237 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1239 #[unstable(feature = "split_inclusive", issue = "72360")]
1241 pub fn split_inclusive
<'a
, P
: Pattern
<'a
>>(&'a
self, pat
: P
) -> SplitInclusive
<'a
, P
> {
1242 SplitInclusive(SplitInternal
{
1245 matcher
: pat
.into_searcher(self),
1246 allow_trailing_empty
: false,
1251 /// An iterator over substrings of the given string slice, separated by
1252 /// characters matched by a pattern and yielded in reverse order.
1254 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1255 /// function or closure that determines if a character matches.
1257 /// [`char`]: prim@char
1258 /// [pattern]: self::pattern
1260 /// # Iterator behavior
1262 /// The returned iterator requires that the pattern supports a reverse
1263 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1264 /// search yields the same elements.
1266 /// For iterating from the front, the [`split`] method can be used.
1268 /// [`split`]: str::split
1272 /// Simple patterns:
1275 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1276 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1278 /// let v: Vec<&str> = "".rsplit('X').collect();
1279 /// assert_eq!(v, [""]);
1281 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1282 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1284 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1285 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1288 /// A more complex pattern, using a closure:
1291 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1292 /// assert_eq!(v, ["ghi", "def", "abc"]);
1294 #[stable(feature = "rust1", since = "1.0.0")]
1296 pub fn rsplit
<'a
, P
>(&'a
self, pat
: P
) -> RSplit
<'a
, P
>
1298 P
: Pattern
<'a
, Searcher
: ReverseSearcher
<'a
>>,
1300 RSplit(self.split(pat
).0)
1303 /// An iterator over substrings of the given string slice, separated by
1304 /// characters matched by a pattern.
1306 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1307 /// function or closure that determines if a character matches.
1309 /// [`char`]: prim@char
1310 /// [pattern]: self::pattern
1312 /// Equivalent to [`split`], except that the trailing substring
1313 /// is skipped if empty.
1315 /// [`split`]: str::split
1317 /// This method can be used for string data that is _terminated_,
1318 /// rather than _separated_ by a pattern.
1320 /// # Iterator behavior
1322 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1323 /// allows a reverse search and forward/reverse search yields the same
1324 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1326 /// If the pattern allows a reverse search but its results might differ
1327 /// from a forward search, the [`rsplit_terminator`] method can be used.
1329 /// [`rsplit_terminator`]: str::rsplit_terminator
1336 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1337 /// assert_eq!(v, ["A", "B"]);
1339 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1340 /// assert_eq!(v, ["A", "", "B", ""]);
1342 #[stable(feature = "rust1", since = "1.0.0")]
1344 pub fn split_terminator
<'a
, P
: Pattern
<'a
>>(&'a
self, pat
: P
) -> SplitTerminator
<'a
, P
> {
1345 SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 }
)
1348 /// An iterator over substrings of `self`, separated by characters
1349 /// matched by a pattern and yielded in reverse order.
1351 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1352 /// function or closure that determines if a character matches.
1354 /// [`char`]: prim@char
1355 /// [pattern]: self::pattern
1357 /// Equivalent to [`split`], except that the trailing substring is
1358 /// skipped if empty.
1360 /// [`split`]: str::split
1362 /// This method can be used for string data that is _terminated_,
1363 /// rather than _separated_ by a pattern.
1365 /// # Iterator behavior
1367 /// The returned iterator requires that the pattern supports a
1368 /// reverse search, and it will be double ended if a forward/reverse
1369 /// search yields the same elements.
1371 /// For iterating from the front, the [`split_terminator`] method can be
1374 /// [`split_terminator`]: str::split_terminator
1379 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1380 /// assert_eq!(v, ["B", "A"]);
1382 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1383 /// assert_eq!(v, ["", "B", "", "A"]);
1385 #[stable(feature = "rust1", since = "1.0.0")]
1387 pub fn rsplit_terminator
<'a
, P
>(&'a
self, pat
: P
) -> RSplitTerminator
<'a
, P
>
1389 P
: Pattern
<'a
, Searcher
: ReverseSearcher
<'a
>>,
1391 RSplitTerminator(self.split_terminator(pat
).0)
1394 /// An iterator over substrings of the given string slice, separated by a
1395 /// pattern, restricted to returning at most `n` items.
1397 /// If `n` substrings are returned, the last substring (the `n`th substring)
1398 /// will contain the remainder of the string.
1400 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1401 /// function or closure that determines if a character matches.
1403 /// [`char`]: prim@char
1404 /// [pattern]: self::pattern
1406 /// # Iterator behavior
1408 /// The returned iterator will not be double ended, because it is
1409 /// not efficient to support.
1411 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1414 /// [`rsplitn`]: str::rsplitn
1418 /// Simple patterns:
1421 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1422 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1424 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1425 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1427 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1428 /// assert_eq!(v, ["abcXdef"]);
1430 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1431 /// assert_eq!(v, [""]);
1434 /// A more complex pattern, using a closure:
1437 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1438 /// assert_eq!(v, ["abc", "defXghi"]);
1440 #[stable(feature = "rust1", since = "1.0.0")]
1442 pub fn splitn
<'a
, P
: Pattern
<'a
>>(&'a
self, n
: usize, pat
: P
) -> SplitN
<'a
, P
> {
1443 SplitN(SplitNInternal { iter: self.split(pat).0, count: n }
)
1446 /// An iterator over substrings of this string slice, separated by a
1447 /// pattern, starting from the end of the string, restricted to returning
1448 /// at most `n` items.
1450 /// If `n` substrings are returned, the last substring (the `n`th substring)
1451 /// will contain the remainder of the string.
1453 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1454 /// function or closure that determines if a character matches.
1456 /// [`char`]: prim@char
1457 /// [pattern]: self::pattern
1459 /// # Iterator behavior
1461 /// The returned iterator will not be double ended, because it is not
1462 /// efficient to support.
1464 /// For splitting from the front, the [`splitn`] method can be used.
1466 /// [`splitn`]: str::splitn
1470 /// Simple patterns:
1473 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1474 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1476 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1477 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1479 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1480 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1483 /// A more complex pattern, using a closure:
1486 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1487 /// assert_eq!(v, ["ghi", "abc1def"]);
1489 #[stable(feature = "rust1", since = "1.0.0")]
1491 pub fn rsplitn
<'a
, P
>(&'a
self, n
: usize, pat
: P
) -> RSplitN
<'a
, P
>
1493 P
: Pattern
<'a
, Searcher
: ReverseSearcher
<'a
>>,
1495 RSplitN(self.splitn(n
, pat
).0)
1498 /// Splits the string on the first occurrence of the specified delimiter and
1499 /// returns prefix before delimiter and suffix after delimiter.
1504 /// #![feature(str_split_once)]
1506 /// assert_eq!("cfg".split_once('='), None);
1507 /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1508 /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1510 #[unstable(feature = "str_split_once", reason = "newly added", issue = "74773")]
1512 pub fn split_once
<'a
, P
: Pattern
<'a
>>(&'a
self, delimiter
: P
) -> Option
<(&'a
str, &'a
str)> {
1513 let (start
, end
) = delimiter
.into_searcher(self).next_match()?
;
1514 Some((&self[..start
], &self[end
..]))
1517 /// Splits the string on the last occurrence of the specified delimiter and
1518 /// returns prefix before delimiter and suffix after delimiter.
1523 /// #![feature(str_split_once)]
1525 /// assert_eq!("cfg".rsplit_once('='), None);
1526 /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
1527 /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1529 #[unstable(feature = "str_split_once", reason = "newly added", issue = "74773")]
1531 pub fn rsplit_once
<'a
, P
>(&'a
self, delimiter
: P
) -> Option
<(&'a
str, &'a
str)>
1533 P
: Pattern
<'a
, Searcher
: ReverseSearcher
<'a
>>,
1535 let (start
, end
) = delimiter
.into_searcher(self).next_match_back()?
;
1536 Some((&self[..start
], &self[end
..]))
1539 /// An iterator over the disjoint matches of a pattern within the given string
1542 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1543 /// function or closure that determines if a character matches.
1545 /// [`char`]: prim@char
1546 /// [pattern]: self::pattern
1548 /// # Iterator behavior
1550 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1551 /// allows a reverse search and forward/reverse search yields the same
1552 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1554 /// If the pattern allows a reverse search but its results might differ
1555 /// from a forward search, the [`rmatches`] method can be used.
1557 /// [`rmatches`]: str::matches
1564 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1565 /// assert_eq!(v, ["abc", "abc", "abc"]);
1567 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1568 /// assert_eq!(v, ["1", "2", "3"]);
1570 #[stable(feature = "str_matches", since = "1.2.0")]
1572 pub fn matches
<'a
, P
: Pattern
<'a
>>(&'a
self, pat
: P
) -> Matches
<'a
, P
> {
1573 Matches(MatchesInternal(pat
.into_searcher(self)))
1576 /// An iterator over the disjoint matches of a pattern within this string slice,
1577 /// yielded in reverse order.
1579 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1580 /// function or closure that determines if a character matches.
1582 /// [`char`]: prim@char
1583 /// [pattern]: self::pattern
1585 /// # Iterator behavior
1587 /// The returned iterator requires that the pattern supports a reverse
1588 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1589 /// search yields the same elements.
1591 /// For iterating from the front, the [`matches`] method can be used.
1593 /// [`matches`]: str::matches
1600 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1601 /// assert_eq!(v, ["abc", "abc", "abc"]);
1603 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1604 /// assert_eq!(v, ["3", "2", "1"]);
1606 #[stable(feature = "str_matches", since = "1.2.0")]
1608 pub fn rmatches
<'a
, P
>(&'a
self, pat
: P
) -> RMatches
<'a
, P
>
1610 P
: Pattern
<'a
, Searcher
: ReverseSearcher
<'a
>>,
1612 RMatches(self.matches(pat
).0)
1615 /// An iterator over the disjoint matches of a pattern within this string
1616 /// slice as well as the index that the match starts at.
1618 /// For matches of `pat` within `self` that overlap, only the indices
1619 /// corresponding to the first match are returned.
1621 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1622 /// function or closure that determines if a character matches.
1624 /// [`char`]: prim@char
1625 /// [pattern]: self::pattern
1627 /// # Iterator behavior
1629 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1630 /// allows a reverse search and forward/reverse search yields the same
1631 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1633 /// If the pattern allows a reverse search but its results might differ
1634 /// from a forward search, the [`rmatch_indices`] method can be used.
1636 /// [`rmatch_indices`]: str::match_indices
1643 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1644 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1646 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1647 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1649 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1650 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1652 #[stable(feature = "str_match_indices", since = "1.5.0")]
1654 pub fn match_indices
<'a
, P
: Pattern
<'a
>>(&'a
self, pat
: P
) -> MatchIndices
<'a
, P
> {
1655 MatchIndices(MatchIndicesInternal(pat
.into_searcher(self)))
1658 /// An iterator over the disjoint matches of a pattern within `self`,
1659 /// yielded in reverse order along with the index of the match.
1661 /// For matches of `pat` within `self` that overlap, only the indices
1662 /// corresponding to the last match are returned.
1664 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1665 /// function or closure that determines if a character matches.
1667 /// [`char`]: prim@char
1668 /// [pattern]: self::pattern
1670 /// # Iterator behavior
1672 /// The returned iterator requires that the pattern supports a reverse
1673 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1674 /// search yields the same elements.
1676 /// For iterating from the front, the [`match_indices`] method can be used.
1678 /// [`match_indices`]: str::match_indices
1685 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1686 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1688 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1689 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1691 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1692 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1694 #[stable(feature = "str_match_indices", since = "1.5.0")]
1696 pub fn rmatch_indices
<'a
, P
>(&'a
self, pat
: P
) -> RMatchIndices
<'a
, P
>
1698 P
: Pattern
<'a
, Searcher
: ReverseSearcher
<'a
>>,
1700 RMatchIndices(self.match_indices(pat
).0)
1703 /// Returns a string slice with leading and trailing whitespace removed.
1705 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1706 /// Core Property `White_Space`.
1713 /// let s = " Hello\tworld\t";
1715 /// assert_eq!("Hello\tworld", s.trim());
1718 #[must_use = "this returns the trimmed string as a slice, \
1719 without modifying the original"]
1720 #[stable(feature = "rust1", since = "1.0.0")]
1721 pub fn trim(&self) -> &str {
1722 self.trim_matches(|c
: char| c
.is_whitespace())
1725 /// Returns a string slice with leading whitespace removed.
1727 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1728 /// Core Property `White_Space`.
1730 /// # Text directionality
1732 /// A string is a sequence of bytes. `start` in this context means the first
1733 /// position of that byte string; for a left-to-right language like English or
1734 /// Russian, this will be left side, and for right-to-left languages like
1735 /// Arabic or Hebrew, this will be the right side.
1742 /// let s = " Hello\tworld\t";
1743 /// assert_eq!("Hello\tworld\t", s.trim_start());
1749 /// let s = " English ";
1750 /// assert!(Some('E') == s.trim_start().chars().next());
1752 /// let s = " עברית ";
1753 /// assert!(Some('ע') == s.trim_start().chars().next());
1756 #[must_use = "this returns the trimmed string as a new slice, \
1757 without modifying the original"]
1758 #[stable(feature = "trim_direction", since = "1.30.0")]
1759 pub fn trim_start(&self) -> &str {
1760 self.trim_start_matches(|c
: char| c
.is_whitespace())
1763 /// Returns a string slice with trailing whitespace removed.
1765 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1766 /// Core Property `White_Space`.
1768 /// # Text directionality
1770 /// A string is a sequence of bytes. `end` in this context means the last
1771 /// position of that byte string; for a left-to-right language like English or
1772 /// Russian, this will be right side, and for right-to-left languages like
1773 /// Arabic or Hebrew, this will be the left side.
1780 /// let s = " Hello\tworld\t";
1781 /// assert_eq!(" Hello\tworld", s.trim_end());
1787 /// let s = " English ";
1788 /// assert!(Some('h') == s.trim_end().chars().rev().next());
1790 /// let s = " עברית ";
1791 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
1794 #[must_use = "this returns the trimmed string as a new slice, \
1795 without modifying the original"]
1796 #[stable(feature = "trim_direction", since = "1.30.0")]
1797 pub fn trim_end(&self) -> &str {
1798 self.trim_end_matches(|c
: char| c
.is_whitespace())
1801 /// Returns a string slice with leading whitespace removed.
1803 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1804 /// Core Property `White_Space`.
1806 /// # Text directionality
1808 /// A string is a sequence of bytes. 'Left' in this context means the first
1809 /// position of that byte string; for a language like Arabic or Hebrew
1810 /// which are 'right to left' rather than 'left to right', this will be
1811 /// the _right_ side, not the left.
1818 /// let s = " Hello\tworld\t";
1820 /// assert_eq!("Hello\tworld\t", s.trim_left());
1826 /// let s = " English";
1827 /// assert!(Some('E') == s.trim_left().chars().next());
1829 /// let s = " עברית";
1830 /// assert!(Some('ע') == s.trim_left().chars().next());
1833 #[stable(feature = "rust1", since = "1.0.0")]
1836 reason
= "superseded by `trim_start`",
1837 suggestion
= "trim_start"
1839 pub fn trim_left(&self) -> &str {
1843 /// Returns a string slice with trailing whitespace removed.
1845 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1846 /// Core Property `White_Space`.
1848 /// # Text directionality
1850 /// A string is a sequence of bytes. 'Right' in this context means the last
1851 /// position of that byte string; for a language like Arabic or Hebrew
1852 /// which are 'right to left' rather than 'left to right', this will be
1853 /// the _left_ side, not the right.
1860 /// let s = " Hello\tworld\t";
1862 /// assert_eq!(" Hello\tworld", s.trim_right());
1868 /// let s = "English ";
1869 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1871 /// let s = "עברית ";
1872 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1875 #[stable(feature = "rust1", since = "1.0.0")]
1878 reason
= "superseded by `trim_end`",
1879 suggestion
= "trim_end"
1881 pub fn trim_right(&self) -> &str {
1885 /// Returns a string slice with all prefixes and suffixes that match a
1886 /// pattern repeatedly removed.
1888 /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
1889 /// or closure that determines if a character matches.
1891 /// [`char`]: prim@char
1892 /// [pattern]: self::pattern
1896 /// Simple patterns:
1899 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1900 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1902 /// let x: &[_] = &['1', '2'];
1903 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1906 /// A more complex pattern, using a closure:
1909 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1911 #[must_use = "this returns the trimmed string as a new slice, \
1912 without modifying the original"]
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 pub fn trim_matches
<'a
, P
>(&'a
self, pat
: P
) -> &'a
str
1916 P
: Pattern
<'a
, Searcher
: DoubleEndedSearcher
<'a
>>,
1920 let mut matcher
= pat
.into_searcher(self);
1921 if let Some((a
, b
)) = matcher
.next_reject() {
1923 j
= b
; // Remember earliest known match, correct it below if
1924 // last match is different
1926 if let Some((_
, b
)) = matcher
.next_reject_back() {
1929 // SAFETY: `Searcher` is known to return valid indices.
1930 unsafe { self.get_unchecked(i..j) }
1933 /// Returns a string slice with all prefixes that match a pattern
1934 /// repeatedly removed.
1936 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1937 /// function or closure that determines if a character matches.
1939 /// [`char`]: prim@char
1940 /// [pattern]: self::pattern
1942 /// # Text directionality
1944 /// A string is a sequence of bytes. `start` in this context means the first
1945 /// position of that byte string; for a left-to-right language like English or
1946 /// Russian, this will be left side, and for right-to-left languages like
1947 /// Arabic or Hebrew, this will be the right side.
1954 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
1955 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
1957 /// let x: &[_] = &['1', '2'];
1958 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
1960 #[must_use = "this returns the trimmed string as a new slice, \
1961 without modifying the original"]
1962 #[stable(feature = "trim_direction", since = "1.30.0")]
1963 pub fn trim_start_matches
<'a
, P
: Pattern
<'a
>>(&'a
self, pat
: P
) -> &'a
str {
1964 let mut i
= self.len();
1965 let mut matcher
= pat
.into_searcher(self);
1966 if let Some((a
, _
)) = matcher
.next_reject() {
1969 // SAFETY: `Searcher` is known to return valid indices.
1970 unsafe { self.get_unchecked(i..self.len()) }
1973 /// Returns a string slice with the prefix removed.
1975 /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped
1976 /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once.
1978 /// If the string does not start with `prefix`, returns `None`.
1980 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1981 /// function or closure that determines if a character matches.
1983 /// [`char`]: prim@char
1984 /// [pattern]: self::pattern
1989 /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
1990 /// assert_eq!("foo:bar".strip_prefix("bar"), None);
1991 /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
1993 #[must_use = "this returns the remaining substring as a new slice, \
1994 without modifying the original"]
1995 #[stable(feature = "str_strip", since = "1.45.0")]
1996 pub fn strip_prefix
<'a
, P
: Pattern
<'a
>>(&'a
self, prefix
: P
) -> Option
<&'a
str> {
1997 prefix
.strip_prefix_of(self)
2000 /// Returns a string slice with the suffix removed.
2002 /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2003 /// wrapped in `Some`. Unlike `trim_end_matches`, this method removes the suffix exactly once.
2005 /// If the string does not end with `suffix`, returns `None`.
2007 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2008 /// function or closure that determines if a character matches.
2010 /// [`char`]: prim@char
2011 /// [pattern]: self::pattern
2016 /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2017 /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2018 /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2020 #[must_use = "this returns the remaining substring as a new slice, \
2021 without modifying the original"]
2022 #[stable(feature = "str_strip", since = "1.45.0")]
2023 pub fn strip_suffix
<'a
, P
>(&'a
self, suffix
: P
) -> Option
<&'a
str>
2026 <P
as Pattern
<'a
>>::Searcher
: ReverseSearcher
<'a
>,
2028 suffix
.strip_suffix_of(self)
2031 /// Returns a string slice with all suffixes that match a pattern
2032 /// repeatedly removed.
2034 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2035 /// function or closure that determines if a character matches.
2037 /// [`char`]: prim@char
2038 /// [pattern]: self::pattern
2040 /// # Text directionality
2042 /// A string is a sequence of bytes. `end` in this context means the last
2043 /// position of that byte string; for a left-to-right language like English or
2044 /// Russian, this will be right side, and for right-to-left languages like
2045 /// Arabic or Hebrew, this will be the left side.
2049 /// Simple patterns:
2052 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2053 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2055 /// let x: &[_] = &['1', '2'];
2056 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2059 /// A more complex pattern, using a closure:
2062 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2064 #[must_use = "this returns the trimmed string as a new slice, \
2065 without modifying the original"]
2066 #[stable(feature = "trim_direction", since = "1.30.0")]
2067 pub fn trim_end_matches
<'a
, P
>(&'a
self, pat
: P
) -> &'a
str
2069 P
: Pattern
<'a
, Searcher
: ReverseSearcher
<'a
>>,
2072 let mut matcher
= pat
.into_searcher(self);
2073 if let Some((_
, b
)) = matcher
.next_reject_back() {
2076 // SAFETY: `Searcher` is known to return valid indices.
2077 unsafe { self.get_unchecked(0..j) }
2080 /// Returns a string slice with all prefixes that match a pattern
2081 /// repeatedly removed.
2083 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2084 /// function or closure that determines if a character matches.
2086 /// [`char`]: prim@char
2087 /// [pattern]: self::pattern
2089 /// # Text directionality
2091 /// A string is a sequence of bytes. 'Left' in this context means the first
2092 /// position of that byte string; for a language like Arabic or Hebrew
2093 /// which are 'right to left' rather than 'left to right', this will be
2094 /// the _right_ side, not the left.
2101 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2102 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2104 /// let x: &[_] = &['1', '2'];
2105 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2107 #[stable(feature = "rust1", since = "1.0.0")]
2110 reason
= "superseded by `trim_start_matches`",
2111 suggestion
= "trim_start_matches"
2113 pub fn trim_left_matches
<'a
, P
: Pattern
<'a
>>(&'a
self, pat
: P
) -> &'a
str {
2114 self.trim_start_matches(pat
)
2117 /// Returns a string slice with all suffixes that match a pattern
2118 /// repeatedly removed.
2120 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2121 /// function or closure that determines if a character matches.
2123 /// [`char`]: prim@char
2124 /// [pattern]: self::pattern
2126 /// # Text directionality
2128 /// A string is a sequence of bytes. 'Right' in this context means the last
2129 /// position of that byte string; for a language like Arabic or Hebrew
2130 /// which are 'right to left' rather than 'left to right', this will be
2131 /// the _left_ side, not the right.
2135 /// Simple patterns:
2138 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2139 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2141 /// let x: &[_] = &['1', '2'];
2142 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2145 /// A more complex pattern, using a closure:
2148 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2150 #[stable(feature = "rust1", since = "1.0.0")]
2153 reason
= "superseded by `trim_end_matches`",
2154 suggestion
= "trim_end_matches"
2156 pub fn trim_right_matches
<'a
, P
>(&'a
self, pat
: P
) -> &'a
str
2158 P
: Pattern
<'a
, Searcher
: ReverseSearcher
<'a
>>,
2160 self.trim_end_matches(pat
)
2163 /// Parses this string slice into another type.
2165 /// Because `parse` is so general, it can cause problems with type
2166 /// inference. As such, `parse` is one of the few times you'll see
2167 /// the syntax affectionately known as the 'turbofish': `::<>`. This
2168 /// helps the inference algorithm understand specifically which type
2169 /// you're trying to parse into.
2171 /// `parse` can parse any type that implements the [`FromStr`] trait.
2176 /// Will return [`Err`] if it's not possible to parse this string slice into
2177 /// the desired type.
2179 /// [`Err`]: FromStr::Err
2186 /// let four: u32 = "4".parse().unwrap();
2188 /// assert_eq!(4, four);
2191 /// Using the 'turbofish' instead of annotating `four`:
2194 /// let four = "4".parse::<u32>();
2196 /// assert_eq!(Ok(4), four);
2199 /// Failing to parse:
2202 /// let nope = "j".parse::<u32>();
2204 /// assert!(nope.is_err());
2207 #[stable(feature = "rust1", since = "1.0.0")]
2208 pub fn parse
<F
: FromStr
>(&self) -> Result
<F
, F
::Err
> {
2209 FromStr
::from_str(self)
2212 /// Checks if all characters in this string are within the ASCII range.
2217 /// let ascii = "hello!\n";
2218 /// let non_ascii = "Grüße, Jürgen ❤";
2220 /// assert!(ascii.is_ascii());
2221 /// assert!(!non_ascii.is_ascii());
2223 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2225 pub fn is_ascii(&self) -> bool
{
2226 // We can treat each byte as character here: all multibyte characters
2227 // start with a byte that is not in the ascii range, so we will stop
2229 self.as_bytes().is_ascii()
2232 /// Checks that two strings are an ASCII case-insensitive match.
2234 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2235 /// but without allocating and copying temporaries.
2240 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2241 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2242 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2244 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2246 pub fn eq_ignore_ascii_case(&self, other
: &str) -> bool
{
2247 self.as_bytes().eq_ignore_ascii_case(other
.as_bytes())
2250 /// Converts this string to its ASCII upper case equivalent in-place.
2252 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2253 /// but non-ASCII letters are unchanged.
2255 /// To return a new uppercased value without modifying the existing one, use
2256 /// [`to_ascii_uppercase`].
2258 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2263 /// let mut s = String::from("Grüße, Jürgen ❤");
2265 /// s.make_ascii_uppercase();
2267 /// assert_eq!("GRüßE, JüRGEN ❤", s);
2269 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2271 pub fn make_ascii_uppercase(&mut self) {
2272 // SAFETY: safe because we transmute two types with the same layout.
2273 let me
= unsafe { self.as_bytes_mut() }
;
2274 me
.make_ascii_uppercase()
2277 /// Converts this string to its ASCII lower case equivalent in-place.
2279 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2280 /// but non-ASCII letters are unchanged.
2282 /// To return a new lowercased value without modifying the existing one, use
2283 /// [`to_ascii_lowercase`].
2285 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2290 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2292 /// s.make_ascii_lowercase();
2294 /// assert_eq!("grÜße, jÜrgen ❤", s);
2296 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2298 pub fn make_ascii_lowercase(&mut self) {
2299 // SAFETY: safe because we transmute two types with the same layout.
2300 let me
= unsafe { self.as_bytes_mut() }
;
2301 me
.make_ascii_lowercase()
2304 /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
2306 /// Note: only extended grapheme codepoints that begin the string will be
2314 /// for c in "❤\n!".escape_debug() {
2315 /// print!("{}", c);
2320 /// Using `println!` directly:
2323 /// println!("{}", "❤\n!".escape_debug());
2327 /// Both are equivalent to:
2330 /// println!("❤\\n!");
2333 /// Using `to_string`:
2336 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
2338 #[stable(feature = "str_escape", since = "1.34.0")]
2339 pub fn escape_debug(&self) -> EscapeDebug
<'_
> {
2340 let mut chars
= self.chars();
2344 .map(|first
| first
.escape_debug_ext(true))
2347 .chain(chars
.flat_map(CharEscapeDebugContinue
)),
2351 /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
2358 /// for c in "❤\n!".escape_default() {
2359 /// print!("{}", c);
2364 /// Using `println!` directly:
2367 /// println!("{}", "❤\n!".escape_default());
2371 /// Both are equivalent to:
2374 /// println!("\\u{{2764}}\\n!");
2377 /// Using `to_string`:
2380 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
2382 #[stable(feature = "str_escape", since = "1.34.0")]
2383 pub fn escape_default(&self) -> EscapeDefault
<'_
> {
2384 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
2387 /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
2394 /// for c in "❤\n!".escape_unicode() {
2395 /// print!("{}", c);
2400 /// Using `println!` directly:
2403 /// println!("{}", "❤\n!".escape_unicode());
2407 /// Both are equivalent to:
2410 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
2413 /// Using `to_string`:
2416 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
2418 #[stable(feature = "str_escape", since = "1.34.0")]
2419 pub fn escape_unicode(&self) -> EscapeUnicode
<'_
> {
2420 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
2424 #[stable(feature = "rust1", since = "1.0.0")]
2425 impl AsRef
<[u8]> for str {
2427 fn as_ref(&self) -> &[u8] {
2432 #[stable(feature = "rust1", since = "1.0.0")]
2433 impl Default
for &str {
2434 /// Creates an empty str
2436 fn default() -> Self {
2441 #[stable(feature = "default_mut_str", since = "1.28.0")]
2442 impl Default
for &mut str {
2443 /// Creates an empty mutable str
2445 fn default() -> Self {
2446 // SAFETY: The empty string is valid UTF-8.
2447 unsafe { from_utf8_unchecked_mut(&mut []) }
2452 /// A nameable, cloneable fn type
2454 struct LinesAnyMap
impl<'a
> Fn
= |line
: &'a
str| -> &'a
str {
2456 if l
> 0 && line
.as_bytes()[l
- 1] == b'
\r' { &line[0 .. l - 1] }
2461 struct CharEscapeDebugContinue
impl Fn
= |c
: char| -> char::EscapeDebug
{
2462 c
.escape_debug_ext(false)
2466 struct CharEscapeUnicode
impl Fn
= |c
: char| -> char::EscapeUnicode
{
2470 struct CharEscapeDefault
impl Fn
= |c
: char| -> char::EscapeDefault
{
2475 struct IsWhitespace
impl Fn
= |c
: char| -> bool
{
2480 struct IsAsciiWhitespace
impl Fn
= |byte
: &u8| -> bool
{
2481 byte
.is_ascii_whitespace()
2485 struct IsNotEmpty
impl<'a
, 'b
> Fn
= |s
: &'a
&'b
str| -> bool
{
2490 struct BytesIsNotEmpty
impl<'a
, 'b
> Fn
= |s
: &'a
&'b
[u8]| -> bool
{
2495 struct UnsafeBytesToStr
impl<'a
> Fn
= |bytes
: &'a
[u8]| -> &'a
str {
2497 unsafe { from_utf8_unchecked(bytes) }