core/str/mod.rs
1//! String manipulation.
2//!
3//! For more details, see the [`std::str`] module.
4//!
5//! [`std::str`]: ../../std/str/index.html
6
7#![stable(feature = "rust1", since = "1.0.0")]
8
9mod converts;
10mod count;
11mod error;
12mod iter;
13mod traits;
14mod validations;
15
16use self::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher};
17use crate::char::{self, EscapeDebugExtArgs};
18use crate::ops::Range;
19use crate::slice::{self, SliceIndex};
20use crate::ub_checks::assert_unsafe_precondition;
21use crate::{ascii, mem};
22
23pub mod pattern;
24
25mod lossy;
26#[unstable(feature = "str_from_raw_parts", issue = "119206")]
27pub use converts::{from_raw_parts, from_raw_parts_mut};
28#[stable(feature = "rust1", since = "1.0.0")]
29pub use converts::{from_utf8, from_utf8_unchecked};
30#[stable(feature = "str_mut_extras", since = "1.20.0")]
31pub use converts::{from_utf8_mut, from_utf8_unchecked_mut};
32#[stable(feature = "rust1", since = "1.0.0")]
33pub use error::{ParseBoolError, Utf8Error};
34#[stable(feature = "encode_utf16", since = "1.8.0")]
35pub use iter::EncodeUtf16;
36#[stable(feature = "rust1", since = "1.0.0")]
37#[allow(deprecated)]
38pub use iter::LinesAny;
39#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
40pub use iter::SplitAsciiWhitespace;
41#[stable(feature = "split_inclusive", since = "1.51.0")]
42pub use iter::SplitInclusive;
43#[stable(feature = "rust1", since = "1.0.0")]
44pub use iter::{Bytes, CharIndices, Chars, Lines, SplitWhitespace};
45#[stable(feature = "str_escape", since = "1.34.0")]
46pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode};
47#[stable(feature = "str_match_indices", since = "1.5.0")]
48pub use iter::{MatchIndices, RMatchIndices};
49use iter::{MatchIndicesInternal, MatchesInternal, SplitInternal, SplitNInternal};
50#[stable(feature = "str_matches", since = "1.2.0")]
51pub use iter::{Matches, RMatches};
52#[stable(feature = "rust1", since = "1.0.0")]
53pub use iter::{RSplit, RSplitTerminator, Split, SplitTerminator};
54#[stable(feature = "rust1", since = "1.0.0")]
55pub use iter::{RSplitN, SplitN};
56#[stable(feature = "utf8_chunks", since = "1.79.0")]
57pub use lossy::{Utf8Chunk, Utf8Chunks};
58#[stable(feature = "rust1", since = "1.0.0")]
59pub use traits::FromStr;
60#[unstable(feature = "str_internals", issue = "none")]
61pub use validations::{next_code_point, utf8_char_width};
62
63#[inline(never)]
64#[cold]
65#[track_caller]
66#[rustc_allow_const_fn_unstable(const_eval_select)]
67#[cfg(not(panic = "immediate-abort"))]
68#[ferrocene::prevalidated]
69const fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
70 crate::intrinsics::const_eval_select((s, begin, end), slice_error_fail_ct, slice_error_fail_rt)
71}
72
73#[cfg(panic = "immediate-abort")]
74const fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
75 slice_error_fail_ct(s, begin, end)
76}
77
78#[track_caller]
79#[ferrocene::annotation("Cannot be covered as this only runs during compilation.")]
80#[ferrocene::prevalidated]
81const fn slice_error_fail_ct(_: &str, _: usize, _: usize) -> ! {
82 panic!("failed to slice string");
83}
84
85#[track_caller]
86#[ferrocene::prevalidated]
87fn slice_error_fail_rt(s: &str, begin: usize, end: usize) -> ! {
88 let len = s.len();
89
90 // 1. begin is OOB.
91 if begin > len {
92 panic!("start byte index {begin} is out of bounds for string of length {len}");
93 }
94
95 // 2. end is OOB.
96 if end > len {
97 panic!("end byte index {end} is out of bounds for string of length {len}");
98 }
99
100 // 3. range is backwards.
101 if begin > end {
102 panic!("byte range starts at {begin} but ends at {end}");
103 }
104
105 // 4. begin is inside a character.
106 if !s.is_char_boundary(begin) {
107 let floor = s.floor_char_boundary(begin);
108 let ceil = s.ceil_char_boundary(begin);
109 let range = floor..ceil;
110 let ch = s[floor..ceil].chars().next().unwrap();
111 panic!(
112 "start byte index {begin} is not a char boundary; it is inside {ch:?} (bytes {range:?} of string)"
113 )
114 }
115
116 // 5. end is inside a character.
117 if !s.is_char_boundary(end) {
118 let floor = s.floor_char_boundary(end);
119 let ceil = s.ceil_char_boundary(end);
120 let range = floor..ceil;
121 let ch = s[floor..ceil].chars().next().unwrap();
122 panic!(
123 "end byte index {end} is not a char boundary; it is inside {ch:?} (bytes {range:?} of string)"
124 )
125 }
126
127 // 6. end is OOB and range is inclusive (end == len).
128 // This test cannot be combined with 2. above because for cases like
129 // `"abcαβγ"[4..9]` the error is that 4 is inside 'α', not that 9 is OOB.
130 debug_assert_eq!(end, len);
131 panic!("end byte index {end} is out of bounds for string of length {len}");
132}
133
134impl str {
135 /// Returns the length of `self`.
136 ///
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.
139 ///
140 /// [`char`]: prim@char
141 ///
142 /// # Examples
143 ///
144 /// ```
145 /// let len = "foo".len();
146 /// assert_eq!(3, len);
147 ///
148 /// assert_eq!("ƒoo".len(), 4); // fancy f!
149 /// assert_eq!("ƒoo".chars().count(), 3);
150 /// ```
151 #[stable(feature = "rust1", since = "1.0.0")]
152 #[rustc_const_stable(feature = "const_str_len", since = "1.39.0")]
153 #[rustc_diagnostic_item = "str_len"]
154 #[rustc_no_implicit_autorefs]
155 #[must_use]
156 #[inline]
157 #[ferrocene::prevalidated]
158 pub const fn len(&self) -> usize {
159 self.as_bytes().len()
160 }
161
162 /// Returns `true` if `self` has a length of zero bytes.
163 ///
164 /// # Examples
165 ///
166 /// ```
167 /// let s = "";
168 /// assert!(s.is_empty());
169 ///
170 /// let s = "not empty";
171 /// assert!(!s.is_empty());
172 /// ```
173 #[stable(feature = "rust1", since = "1.0.0")]
174 #[rustc_const_stable(feature = "const_str_is_empty", since = "1.39.0")]
175 #[rustc_no_implicit_autorefs]
176 #[must_use]
177 #[inline]
178 #[ferrocene::prevalidated]
179 pub const fn is_empty(&self) -> bool {
180 self.len() == 0
181 }
182
183 /// Converts a slice of bytes to a string slice.
184 ///
185 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
186 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
187 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
188 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
189 /// UTF-8, and then does the conversion.
190 ///
191 /// [`&str`]: str
192 /// [byteslice]: prim@slice
193 ///
194 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
195 /// incur the overhead of the validity check, there is an unsafe version of
196 /// this function, [`from_utf8_unchecked`], which has the same
197 /// behavior but skips the check.
198 ///
199 /// If you need a `String` instead of a `&str`, consider
200 /// [`String::from_utf8`][string].
201 ///
202 /// [string]: ../std/string/struct.String.html#method.from_utf8
203 ///
204 /// Because you can stack-allocate a `[u8; N]`, and you can take a
205 /// [`&[u8]`][byteslice] of it, this function is one way to have a
206 /// stack-allocated string. There is an example of this in the
207 /// examples section below.
208 ///
209 /// [byteslice]: slice
210 ///
211 /// # Errors
212 ///
213 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
214 /// provided slice is not UTF-8.
215 ///
216 /// # Examples
217 ///
218 /// Basic usage:
219 ///
220 /// ```
221 /// // some bytes, in a vector
222 /// let sparkle_heart = vec![240, 159, 146, 150];
223 ///
224 /// // We can use the ? (try) operator to check if the bytes are valid
225 /// let sparkle_heart = str::from_utf8(&sparkle_heart)?;
226 ///
227 /// assert_eq!("💖", sparkle_heart);
228 /// # Ok::<_, std::str::Utf8Error>(())
229 /// ```
230 ///
231 /// Incorrect bytes:
232 ///
233 /// ```
234 /// // some invalid bytes, in a vector
235 /// let sparkle_heart = vec![0, 159, 146, 150];
236 ///
237 /// assert!(str::from_utf8(&sparkle_heart).is_err());
238 /// ```
239 ///
240 /// See the docs for [`Utf8Error`] for more details on the kinds of
241 /// errors that can be returned.
242 ///
243 /// A "stack allocated string":
244 ///
245 /// ```
246 /// // some bytes, in a stack-allocated array
247 /// let sparkle_heart = [240, 159, 146, 150];
248 ///
249 /// // We know these bytes are valid, so just use `unwrap()`.
250 /// let sparkle_heart: &str = str::from_utf8(&sparkle_heart).unwrap();
251 ///
252 /// assert_eq!("💖", sparkle_heart);
253 /// ```
254 #[stable(feature = "inherent_str_constructors", since = "1.87.0")]
255 #[rustc_const_stable(feature = "inherent_str_constructors", since = "1.87.0")]
256 #[rustc_diagnostic_item = "str_inherent_from_utf8"]
257 #[ferrocene::prevalidated]
258 pub const fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
259 converts::from_utf8(v)
260 }
261
262 /// Converts a mutable slice of bytes to a mutable string slice.
263 ///
264 /// # Examples
265 ///
266 /// Basic usage:
267 ///
268 /// ```
269 /// // "Hello, Rust!" as a mutable vector
270 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
271 ///
272 /// // As we know these bytes are valid, we can use `unwrap()`
273 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
274 ///
275 /// assert_eq!("Hello, Rust!", outstr);
276 /// ```
277 ///
278 /// Incorrect bytes:
279 ///
280 /// ```
281 /// // Some invalid bytes in a mutable vector
282 /// let mut invalid = vec![128, 223];
283 ///
284 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
285 /// ```
286 /// See the docs for [`Utf8Error`] for more details on the kinds of
287 /// errors that can be returned.
288 #[stable(feature = "inherent_str_constructors", since = "1.87.0")]
289 #[rustc_const_stable(feature = "const_str_from_utf8", since = "1.87.0")]
290 #[rustc_diagnostic_item = "str_inherent_from_utf8_mut"]
291 #[ferrocene::prevalidated]
292 pub const fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
293 converts::from_utf8_mut(v)
294 }
295
296 /// Converts a slice of bytes to a string slice without checking
297 /// that the string contains valid UTF-8.
298 ///
299 /// See the safe version, [`from_utf8`], for more information.
300 ///
301 /// # Safety
302 ///
303 /// The bytes passed in must be valid UTF-8.
304 ///
305 /// # Examples
306 ///
307 /// Basic usage:
308 ///
309 /// ```
310 /// // some bytes, in a vector
311 /// let sparkle_heart = vec![240, 159, 146, 150];
312 ///
313 /// let sparkle_heart = unsafe {
314 /// str::from_utf8_unchecked(&sparkle_heart)
315 /// };
316 ///
317 /// assert_eq!("💖", sparkle_heart);
318 /// ```
319 #[inline]
320 #[must_use]
321 #[stable(feature = "inherent_str_constructors", since = "1.87.0")]
322 #[rustc_const_stable(feature = "inherent_str_constructors", since = "1.87.0")]
323 #[rustc_diagnostic_item = "str_inherent_from_utf8_unchecked"]
324 #[ferrocene::prevalidated]
325 pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
326 // SAFETY: converts::from_utf8_unchecked has the same safety requirements as this function.
327 unsafe { converts::from_utf8_unchecked(v) }
328 }
329
330 /// Converts a slice of bytes to a string slice without checking
331 /// that the string contains valid UTF-8; mutable version.
332 ///
333 /// See the immutable version, [`from_utf8_unchecked()`] for documentation and safety requirements.
334 ///
335 /// # Examples
336 ///
337 /// Basic usage:
338 ///
339 /// ```
340 /// let mut heart = vec![240, 159, 146, 150];
341 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
342 ///
343 /// assert_eq!("💖", heart);
344 /// ```
345 #[inline]
346 #[must_use]
347 #[stable(feature = "inherent_str_constructors", since = "1.87.0")]
348 #[rustc_const_stable(feature = "inherent_str_constructors", since = "1.87.0")]
349 #[rustc_diagnostic_item = "str_inherent_from_utf8_unchecked_mut"]
350 #[ferrocene::prevalidated]
351 pub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
352 // SAFETY: converts::from_utf8_unchecked_mut has the same safety requirements as this function.
353 unsafe { converts::from_utf8_unchecked_mut(v) }
354 }
355
356 /// Checks that `index`-th byte is the first byte in a UTF-8 code point
357 /// sequence or the end of the string.
358 ///
359 /// The start and end of the string (when `index == self.len()`) are
360 /// considered to be boundaries.
361 ///
362 /// Returns `false` if `index` is greater than `self.len()`.
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// let s = "Löwe 老虎 Léopard";
368 /// assert!(s.is_char_boundary(0));
369 /// // start of `老`
370 /// assert!(s.is_char_boundary(6));
371 /// assert!(s.is_char_boundary(s.len()));
372 ///
373 /// // second byte of `ö`
374 /// assert!(!s.is_char_boundary(2));
375 ///
376 /// // third byte of `老`
377 /// assert!(!s.is_char_boundary(8));
378 /// ```
379 #[must_use]
380 #[stable(feature = "is_char_boundary", since = "1.9.0")]
381 #[rustc_const_stable(feature = "const_is_char_boundary", since = "1.86.0")]
382 #[inline]
383 #[ferrocene::prevalidated]
384 pub const fn is_char_boundary(&self, index: usize) -> bool {
385 // 0 is always ok.
386 // Test for 0 explicitly so that it can optimize out the check
387 // easily and skip reading string data for that case.
388 // Note that optimizing `self.get(..index)` relies on this.
389 if index == 0 {
390 return true;
391 }
392
393 if index >= self.len() {
394 // For `true` we have two options:
395 //
396 // - index == self.len()
397 // Empty strings are valid, so return true
398 // - index > self.len()
399 // In this case return false
400 //
401 // The check is placed exactly here, because it improves generated
402 // code on higher opt-levels. See PR #84751 for more details.
403 index == self.len()
404 } else {
405 self.as_bytes()[index].is_utf8_char_boundary()
406 }
407 }
408
409 /// Finds the closest `x` not exceeding `index` where [`is_char_boundary(x)`] is `true`.
410 ///
411 /// This method can help you truncate a string so that it's still valid UTF-8, but doesn't
412 /// exceed a given number of bytes. Note that this is done purely at the character level
413 /// and can still visually split graphemes, even though the underlying characters aren't
414 /// split. For example, the emoji 🧑🔬 (scientist) could be split so that the string only
415 /// includes 🧑 (person) instead.
416 ///
417 /// [`is_char_boundary(x)`]: Self::is_char_boundary
418 ///
419 /// # Examples
420 ///
421 /// ```
422 /// let s = "❤️🧡💛💚💙💜";
423 /// assert_eq!(s.len(), 26);
424 /// assert!(!s.is_char_boundary(13));
425 ///
426 /// let closest = s.floor_char_boundary(13);
427 /// assert_eq!(closest, 10);
428 /// assert_eq!(&s[..closest], "❤️🧡");
429 /// ```
430 #[stable(feature = "round_char_boundary", since = "1.91.0")]
431 #[rustc_const_stable(feature = "round_char_boundary", since = "1.91.0")]
432 #[inline]
433 #[ferrocene::prevalidated]
434 pub const fn floor_char_boundary(&self, index: usize) -> usize {
435 if index >= self.len() {
436 self.len()
437 } else {
438 let mut i = index;
439 while i > 0 {
440 if self.as_bytes()[i].is_utf8_char_boundary() {
441 break;
442 }
443 i -= 1;
444 }
445
446 // The character boundary will be within four bytes of the index
447 debug_assert!(i >= index.saturating_sub(3));
448
449 i
450 }
451 }
452
453 /// Finds the closest `x` not below `index` where [`is_char_boundary(x)`] is `true`.
454 ///
455 /// If `index` is greater than the length of the string, this returns the length of the string.
456 ///
457 /// This method is the natural complement to [`floor_char_boundary`]. See that method
458 /// for more details.
459 ///
460 /// [`floor_char_boundary`]: str::floor_char_boundary
461 /// [`is_char_boundary(x)`]: Self::is_char_boundary
462 ///
463 /// # Examples
464 ///
465 /// ```
466 /// let s = "❤️🧡💛💚💙💜";
467 /// assert_eq!(s.len(), 26);
468 /// assert!(!s.is_char_boundary(13));
469 ///
470 /// let closest = s.ceil_char_boundary(13);
471 /// assert_eq!(closest, 14);
472 /// assert_eq!(&s[..closest], "❤️🧡💛");
473 /// ```
474 #[stable(feature = "round_char_boundary", since = "1.91.0")]
475 #[rustc_const_stable(feature = "round_char_boundary", since = "1.91.0")]
476 #[inline]
477 #[ferrocene::prevalidated]
478 pub const fn ceil_char_boundary(&self, index: usize) -> usize {
479 if index >= self.len() {
480 self.len()
481 } else {
482 let mut i = index;
483 while i < self.len() {
484 if self.as_bytes()[i].is_utf8_char_boundary() {
485 break;
486 }
487 i += 1;
488 }
489
490 // The character boundary will be within four bytes of the index
491 debug_assert!(i <= index + 3);
492
493 i
494 }
495 }
496
497 /// Converts a string slice to a byte slice. To convert the byte slice back
498 /// into a string slice, use the [`from_utf8`] function.
499 ///
500 /// # Examples
501 ///
502 /// ```
503 /// let bytes = "bors".as_bytes();
504 /// assert_eq!(b"bors", bytes);
505 /// ```
506 #[stable(feature = "rust1", since = "1.0.0")]
507 #[rustc_const_stable(feature = "str_as_bytes", since = "1.39.0")]
508 #[must_use]
509 #[inline(always)]
510 #[allow(unused_attributes)]
511 #[ferrocene::prevalidated]
512 pub const fn as_bytes(&self) -> &[u8] {
513 // SAFETY: const sound because we transmute two types with the same layout
514 unsafe { mem::transmute(self) }
515 }
516
517 /// Converts a mutable string slice to a mutable byte slice.
518 ///
519 /// # Safety
520 ///
521 /// The caller must ensure that the content of the slice is valid UTF-8
522 /// before the borrow ends and the underlying `str` is used.
523 ///
524 /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
525 ///
526 /// # Examples
527 ///
528 /// Basic usage:
529 ///
530 /// ```
531 /// let mut s = String::from("Hello");
532 /// let bytes = unsafe { s.as_bytes_mut() };
533 ///
534 /// assert_eq!(b"Hello", bytes);
535 /// ```
536 ///
537 /// Mutability:
538 ///
539 /// ```
540 /// let mut s = String::from("🗻∈🌏");
541 ///
542 /// unsafe {
543 /// let bytes = s.as_bytes_mut();
544 ///
545 /// bytes[0] = 0xF0;
546 /// bytes[1] = 0x9F;
547 /// bytes[2] = 0x8D;
548 /// bytes[3] = 0x94;
549 /// }
550 ///
551 /// assert_eq!("🍔∈🌏", s);
552 /// ```
553 #[stable(feature = "str_mut_extras", since = "1.20.0")]
554 #[rustc_const_stable(feature = "const_str_as_mut", since = "1.83.0")]
555 #[must_use]
556 #[inline(always)]
557 #[ferrocene::prevalidated]
558 pub const unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
559 // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
560 // has the same layout as `&[u8]` (only std can make this guarantee).
561 // The pointer dereference is safe since it comes from a mutable reference which
562 // is guaranteed to be valid for writes.
563 unsafe { &mut *(self as *mut str as *mut [u8]) }
564 }
565
566 /// Converts a string slice to a raw pointer.
567 ///
568 /// As string slices are a slice of bytes, the raw pointer points to a
569 /// [`u8`]. This pointer will be pointing to the first byte of the string
570 /// slice.
571 ///
572 /// The caller must ensure that the returned pointer is never written to.
573 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
574 ///
575 /// [`as_mut_ptr`]: str::as_mut_ptr
576 ///
577 /// # Examples
578 ///
579 /// ```
580 /// let s = "Hello";
581 /// let ptr = s.as_ptr();
582 /// ```
583 #[stable(feature = "rust1", since = "1.0.0")]
584 #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
585 #[rustc_never_returns_null_ptr]
586 #[rustc_as_ptr]
587 #[must_use]
588 #[inline(always)]
589 #[ferrocene::prevalidated]
590 pub const fn as_ptr(&self) -> *const u8 {
591 self as *const str as *const u8
592 }
593
594 /// Converts a mutable string slice to a raw pointer.
595 ///
596 /// As string slices are a slice of bytes, the raw pointer points to a
597 /// [`u8`]. This pointer will be pointing to the first byte of the string
598 /// slice.
599 ///
600 /// It is your responsibility to make sure that the string slice only gets
601 /// modified in a way that it remains valid UTF-8.
602 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
603 #[rustc_const_stable(feature = "const_str_as_mut", since = "1.83.0")]
604 #[rustc_never_returns_null_ptr]
605 #[rustc_as_ptr]
606 #[must_use]
607 #[inline(always)]
608 #[ferrocene::prevalidated]
609 pub const fn as_mut_ptr(&mut self) -> *mut u8 {
610 self as *mut str as *mut u8
611 }
612
613 /// Returns a subslice of `str`.
614 ///
615 /// This is the non-panicking alternative to indexing the `str`. Returns
616 /// [`None`] whenever equivalent indexing operation would panic.
617 ///
618 /// # Examples
619 ///
620 /// ```
621 /// let v = String::from("🗻∈🌏");
622 ///
623 /// assert_eq!(Some("🗻"), v.get(0..4));
624 ///
625 /// // indices not on UTF-8 sequence boundaries
626 /// assert!(v.get(1..).is_none());
627 /// assert!(v.get(..8).is_none());
628 ///
629 /// // out of bounds
630 /// assert!(v.get(..42).is_none());
631 /// ```
632 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
633 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
634 #[inline]
635 pub const fn get<I: [const] SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
636 i.get(self)
637 }
638
639 /// Returns a mutable subslice of `str`.
640 ///
641 /// This is the non-panicking alternative to indexing the `str`. Returns
642 /// [`None`] whenever equivalent indexing operation would panic.
643 ///
644 /// # Examples
645 ///
646 /// ```
647 /// let mut v = String::from("hello");
648 /// // correct length
649 /// assert!(v.get_mut(0..5).is_some());
650 /// // out of bounds
651 /// assert!(v.get_mut(..42).is_none());
652 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
653 ///
654 /// assert_eq!("hello", v);
655 /// {
656 /// let s = v.get_mut(0..2);
657 /// let s = s.map(|s| {
658 /// s.make_ascii_uppercase();
659 /// &*s
660 /// });
661 /// assert_eq!(Some("HE"), s);
662 /// }
663 /// assert_eq!("HEllo", v);
664 /// ```
665 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
666 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
667 #[inline]
668 pub const fn get_mut<I: [const] SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
669 i.get_mut(self)
670 }
671
672 /// Returns an unchecked subslice of `str`.
673 ///
674 /// This is the unchecked alternative to indexing the `str`.
675 ///
676 /// # Safety
677 ///
678 /// Callers of this function are responsible that these preconditions are
679 /// satisfied:
680 ///
681 /// * The starting index must not exceed the ending index;
682 /// * Indexes must be within bounds of the original slice;
683 /// * Indexes must lie on UTF-8 sequence boundaries.
684 ///
685 /// Failing that, the returned string slice may reference invalid memory or
686 /// violate the invariants communicated by the `str` type.
687 ///
688 /// # Examples
689 ///
690 /// ```
691 /// let v = "🗻∈🌏";
692 /// unsafe {
693 /// assert_eq!("🗻", v.get_unchecked(0..4));
694 /// assert_eq!("∈", v.get_unchecked(4..7));
695 /// assert_eq!("🌏", v.get_unchecked(7..11));
696 /// }
697 /// ```
698 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
699 #[inline]
700 #[ferrocene::prevalidated]
701 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
702 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
703 // the slice is dereferenceable because `self` is a safe reference.
704 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
705 unsafe { &*i.get_unchecked(self) }
706 }
707
708 /// Returns a mutable, unchecked subslice of `str`.
709 ///
710 /// This is the unchecked alternative to indexing the `str`.
711 ///
712 /// # Safety
713 ///
714 /// Callers of this function are responsible that these preconditions are
715 /// satisfied:
716 ///
717 /// * The starting index must not exceed the ending index;
718 /// * Indexes must be within bounds of the original slice;
719 /// * Indexes must lie on UTF-8 sequence boundaries.
720 ///
721 /// Failing that, the returned string slice may reference invalid memory or
722 /// violate the invariants communicated by the `str` type.
723 ///
724 /// # Examples
725 ///
726 /// ```
727 /// let mut v = String::from("🗻∈🌏");
728 /// unsafe {
729 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
730 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
731 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
732 /// }
733 /// ```
734 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
735 #[inline]
736 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
737 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
738 // the slice is dereferenceable because `self` is a safe reference.
739 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
740 unsafe { &mut *i.get_unchecked_mut(self) }
741 }
742
743 /// Creates a string slice from another string slice, bypassing safety
744 /// checks.
745 ///
746 /// This is generally not recommended, use with caution! For a safe
747 /// alternative see [`str`] and [`Index`].
748 ///
749 /// [`Index`]: crate::ops::Index
750 ///
751 /// This new slice goes from `begin` to `end`, including `begin` but
752 /// excluding `end`.
753 ///
754 /// To get a mutable string slice instead, see the
755 /// [`slice_mut_unchecked`] method.
756 ///
757 /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
758 ///
759 /// # Safety
760 ///
761 /// Callers of this function are responsible that three preconditions are
762 /// satisfied:
763 ///
764 /// * `begin` must not exceed `end`.
765 /// * `begin` and `end` must be byte positions within the string slice.
766 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
767 ///
768 /// # Examples
769 ///
770 /// ```
771 /// let s = "Löwe 老虎 Léopard";
772 ///
773 /// unsafe {
774 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
775 /// }
776 ///
777 /// let s = "Hello, world!";
778 ///
779 /// unsafe {
780 /// assert_eq!("world", s.slice_unchecked(7, 12));
781 /// }
782 /// ```
783 #[stable(feature = "rust1", since = "1.0.0")]
784 #[deprecated(since = "1.29.0", note = "use `get_unchecked(begin..end)` instead")]
785 #[must_use]
786 #[inline]
787 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
788 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
789 // the slice is dereferenceable because `self` is a safe reference.
790 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
791 unsafe { &*(begin..end).get_unchecked(self) }
792 }
793
794 /// Creates a string slice from another string slice, bypassing safety
795 /// checks.
796 ///
797 /// This is generally not recommended, use with caution! For a safe
798 /// alternative see [`str`] and [`IndexMut`].
799 ///
800 /// [`IndexMut`]: crate::ops::IndexMut
801 ///
802 /// This new slice goes from `begin` to `end`, including `begin` but
803 /// excluding `end`.
804 ///
805 /// To get an immutable string slice instead, see the
806 /// [`slice_unchecked`] method.
807 ///
808 /// [`slice_unchecked`]: str::slice_unchecked
809 ///
810 /// # Safety
811 ///
812 /// Callers of this function are responsible that three preconditions are
813 /// satisfied:
814 ///
815 /// * `begin` must not exceed `end`.
816 /// * `begin` and `end` must be byte positions within the string slice.
817 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
818 #[stable(feature = "str_slice_mut", since = "1.5.0")]
819 #[deprecated(since = "1.29.0", note = "use `get_unchecked_mut(begin..end)` instead")]
820 #[inline]
821 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
822 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
823 // the slice is dereferenceable because `self` is a safe reference.
824 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
825 unsafe { &mut *(begin..end).get_unchecked_mut(self) }
826 }
827
828 /// Divides one string slice into two at an index.
829 ///
830 /// The argument, `mid`, should be a byte offset from the start of the
831 /// string. It must also be on the boundary of a UTF-8 code point.
832 ///
833 /// The two slices returned go from the start of the string slice to `mid`,
834 /// and from `mid` to the end of the string slice.
835 ///
836 /// To get mutable string slices instead, see the [`split_at_mut`]
837 /// method.
838 ///
839 /// [`split_at_mut`]: str::split_at_mut
840 ///
841 /// # Panics
842 ///
843 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is past
844 /// the end of the last code point of the string slice. For a non-panicking
845 /// alternative see [`split_at_checked`](str::split_at_checked).
846 ///
847 /// # Examples
848 ///
849 /// ```
850 /// let s = "Per Martin-Löf";
851 ///
852 /// let (first, last) = s.split_at(3);
853 ///
854 /// assert_eq!("Per", first);
855 /// assert_eq!(" Martin-Löf", last);
856 /// ```
857 #[inline]
858 #[must_use]
859 #[stable(feature = "str_split_at", since = "1.4.0")]
860 #[rustc_const_stable(feature = "const_str_split_at", since = "1.86.0")]
861 pub const fn split_at(&self, mid: usize) -> (&str, &str) {
862 match self.split_at_checked(mid) {
863 None => slice_error_fail(self, 0, mid),
864 Some(pair) => pair,
865 }
866 }
867
868 /// Divides one mutable string slice into two at an index.
869 ///
870 /// The argument, `mid`, should be a byte offset from the start of the
871 /// string. It must also be on the boundary of a UTF-8 code point.
872 ///
873 /// The two slices returned go from the start of the string slice to `mid`,
874 /// and from `mid` to the end of the string slice.
875 ///
876 /// To get immutable string slices instead, see the [`split_at`] method.
877 ///
878 /// [`split_at`]: str::split_at
879 ///
880 /// # Panics
881 ///
882 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is past
883 /// the end of the last code point of the string slice. For a non-panicking
884 /// alternative see [`split_at_mut_checked`](str::split_at_mut_checked).
885 ///
886 /// # Examples
887 ///
888 /// ```
889 /// let mut s = "Per Martin-Löf".to_string();
890 /// {
891 /// let (first, last) = s.split_at_mut(3);
892 /// first.make_ascii_uppercase();
893 /// assert_eq!("PER", first);
894 /// assert_eq!(" Martin-Löf", last);
895 /// }
896 /// assert_eq!("PER Martin-Löf", s);
897 /// ```
898 #[inline]
899 #[must_use]
900 #[stable(feature = "str_split_at", since = "1.4.0")]
901 #[rustc_const_stable(feature = "const_str_split_at", since = "1.86.0")]
902 pub const fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
903 // is_char_boundary checks that the index is in [0, .len()]
904 if self.is_char_boundary(mid) {
905 // SAFETY: just checked that `mid` is on a char boundary.
906 unsafe { self.split_at_mut_unchecked(mid) }
907 } else {
908 slice_error_fail(self, 0, mid)
909 }
910 }
911
912 /// Divides one string slice into two at an index.
913 ///
914 /// The argument, `mid`, should be a valid byte offset from the start of the
915 /// string. It must also be on the boundary of a UTF-8 code point. The
916 /// method returns `None` if that’s not the case.
917 ///
918 /// The two slices returned go from the start of the string slice to `mid`,
919 /// and from `mid` to the end of the string slice.
920 ///
921 /// To get mutable string slices instead, see the [`split_at_mut_checked`]
922 /// method.
923 ///
924 /// [`split_at_mut_checked`]: str::split_at_mut_checked
925 ///
926 /// # Examples
927 ///
928 /// ```
929 /// let s = "Per Martin-Löf";
930 ///
931 /// let (first, last) = s.split_at_checked(3).unwrap();
932 /// assert_eq!("Per", first);
933 /// assert_eq!(" Martin-Löf", last);
934 ///
935 /// assert_eq!(None, s.split_at_checked(13)); // Inside “ö”
936 /// assert_eq!(None, s.split_at_checked(16)); // Beyond the string length
937 /// ```
938 #[inline]
939 #[must_use]
940 #[stable(feature = "split_at_checked", since = "1.80.0")]
941 #[rustc_const_stable(feature = "const_str_split_at", since = "1.86.0")]
942 pub const fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)> {
943 // is_char_boundary checks that the index is in [0, .len()]
944 if self.is_char_boundary(mid) {
945 // SAFETY: just checked that `mid` is on a char boundary.
946 Some(unsafe { self.split_at_unchecked(mid) })
947 } else {
948 None
949 }
950 }
951
952 /// Divides one mutable string slice into two at an index.
953 ///
954 /// The argument, `mid`, should be a valid byte offset from the start of the
955 /// string. It must also be on the boundary of a UTF-8 code point. The
956 /// method returns `None` if that’s not the case.
957 ///
958 /// The two slices returned go from the start of the string slice to `mid`,
959 /// and from `mid` to the end of the string slice.
960 ///
961 /// To get immutable string slices instead, see the [`split_at_checked`] method.
962 ///
963 /// [`split_at_checked`]: str::split_at_checked
964 ///
965 /// # Examples
966 ///
967 /// ```
968 /// let mut s = "Per Martin-Löf".to_string();
969 /// if let Some((first, last)) = s.split_at_mut_checked(3) {
970 /// first.make_ascii_uppercase();
971 /// assert_eq!("PER", first);
972 /// assert_eq!(" Martin-Löf", last);
973 /// }
974 /// assert_eq!("PER Martin-Löf", s);
975 ///
976 /// assert_eq!(None, s.split_at_mut_checked(13)); // Inside “ö”
977 /// assert_eq!(None, s.split_at_mut_checked(16)); // Beyond the string length
978 /// ```
979 #[inline]
980 #[must_use]
981 #[stable(feature = "split_at_checked", since = "1.80.0")]
982 #[rustc_const_stable(feature = "const_str_split_at", since = "1.86.0")]
983 pub const fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut str, &mut str)> {
984 // is_char_boundary checks that the index is in [0, .len()]
985 if self.is_char_boundary(mid) {
986 // SAFETY: just checked that `mid` is on a char boundary.
987 Some(unsafe { self.split_at_mut_unchecked(mid) })
988 } else {
989 None
990 }
991 }
992
993 /// Divides one string slice into two at an index.
994 ///
995 /// # Safety
996 ///
997 /// The caller must ensure that `mid` is a valid byte offset from the start
998 /// of the string and falls on the boundary of a UTF-8 code point.
999 #[inline]
1000 const unsafe fn split_at_unchecked(&self, mid: usize) -> (&str, &str) {
1001 let len = self.len();
1002 let ptr = self.as_ptr();
1003 // SAFETY: caller guarantees `mid` is on a char boundary.
1004 unsafe {
1005 (
1006 from_utf8_unchecked(slice::from_raw_parts(ptr, mid)),
1007 from_utf8_unchecked(slice::from_raw_parts(ptr.add(mid), len - mid)),
1008 )
1009 }
1010 }
1011
1012 /// Divides one string slice into two at an index.
1013 ///
1014 /// # Safety
1015 ///
1016 /// The caller must ensure that `mid` is a valid byte offset from the start
1017 /// of the string and falls on the boundary of a UTF-8 code point.
1018 const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut str, &mut str) {
1019 let len = self.len();
1020 let ptr = self.as_mut_ptr();
1021 // SAFETY: caller guarantees `mid` is on a char boundary.
1022 unsafe {
1023 (
1024 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
1025 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
1026 )
1027 }
1028 }
1029
1030 /// Returns an iterator over the [`char`]s of a string slice.
1031 ///
1032 /// As a string slice consists of valid UTF-8, we can iterate through a
1033 /// string slice by [`char`]. This method returns such an iterator.
1034 ///
1035 /// It's important to remember that [`char`] represents a Unicode Scalar
1036 /// Value, and might not match your idea of what a 'character' is. Iteration
1037 /// over grapheme clusters may be what you actually want. This functionality
1038 /// is not provided by Rust's standard library, check crates.io instead.
1039 ///
1040 /// # Examples
1041 ///
1042 /// Basic usage:
1043 ///
1044 /// ```
1045 /// let word = "goodbye";
1046 ///
1047 /// let count = word.chars().count();
1048 /// assert_eq!(7, count);
1049 ///
1050 /// let mut chars = word.chars();
1051 ///
1052 /// assert_eq!(Some('g'), chars.next());
1053 /// assert_eq!(Some('o'), chars.next());
1054 /// assert_eq!(Some('o'), chars.next());
1055 /// assert_eq!(Some('d'), chars.next());
1056 /// assert_eq!(Some('b'), chars.next());
1057 /// assert_eq!(Some('y'), chars.next());
1058 /// assert_eq!(Some('e'), chars.next());
1059 ///
1060 /// assert_eq!(None, chars.next());
1061 /// ```
1062 ///
1063 /// Remember, [`char`]s might not match your intuition about characters:
1064 ///
1065 /// [`char`]: prim@char
1066 ///
1067 /// ```
1068 /// let y = "y̆";
1069 ///
1070 /// let mut chars = y.chars();
1071 ///
1072 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
1073 /// assert_eq!(Some('\u{0306}'), chars.next());
1074 ///
1075 /// assert_eq!(None, chars.next());
1076 /// ```
1077 #[stable(feature = "rust1", since = "1.0.0")]
1078 #[inline]
1079 #[rustc_diagnostic_item = "str_chars"]
1080 #[ferrocene::prevalidated]
1081 pub fn chars(&self) -> Chars<'_> {
1082 Chars { iter: self.as_bytes().iter() }
1083 }
1084
1085 /// Returns an iterator over the [`char`]s of a string slice, and their
1086 /// positions.
1087 ///
1088 /// As a string slice consists of valid UTF-8, we can iterate through a
1089 /// string slice by [`char`]. This method returns an iterator of both
1090 /// these [`char`]s, as well as their byte positions.
1091 ///
1092 /// The iterator yields tuples. The position is first, the [`char`] is
1093 /// second.
1094 ///
1095 /// # Examples
1096 ///
1097 /// Basic usage:
1098 ///
1099 /// ```
1100 /// let word = "goodbye";
1101 ///
1102 /// let count = word.char_indices().count();
1103 /// assert_eq!(7, count);
1104 ///
1105 /// let mut char_indices = word.char_indices();
1106 ///
1107 /// assert_eq!(Some((0, 'g')), char_indices.next());
1108 /// assert_eq!(Some((1, 'o')), char_indices.next());
1109 /// assert_eq!(Some((2, 'o')), char_indices.next());
1110 /// assert_eq!(Some((3, 'd')), char_indices.next());
1111 /// assert_eq!(Some((4, 'b')), char_indices.next());
1112 /// assert_eq!(Some((5, 'y')), char_indices.next());
1113 /// assert_eq!(Some((6, 'e')), char_indices.next());
1114 ///
1115 /// assert_eq!(None, char_indices.next());
1116 /// ```
1117 ///
1118 /// Remember, [`char`]s might not match your intuition about characters:
1119 ///
1120 /// [`char`]: prim@char
1121 ///
1122 /// ```
1123 /// let yes = "y̆es";
1124 ///
1125 /// let mut char_indices = yes.char_indices();
1126 ///
1127 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
1128 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
1129 ///
1130 /// // note the 3 here - the previous character took up two bytes
1131 /// assert_eq!(Some((3, 'e')), char_indices.next());
1132 /// assert_eq!(Some((4, 's')), char_indices.next());
1133 ///
1134 /// assert_eq!(None, char_indices.next());
1135 /// ```
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 #[inline]
1138 #[ferrocene::prevalidated]
1139 pub fn char_indices(&self) -> CharIndices<'_> {
1140 CharIndices { front_offset: 0, iter: self.chars() }
1141 }
1142
1143 /// Returns an iterator over the bytes of a string slice.
1144 ///
1145 /// As a string slice consists of a sequence of bytes, we can iterate
1146 /// through a string slice by byte. This method returns such an iterator.
1147 ///
1148 /// # Examples
1149 ///
1150 /// ```
1151 /// let mut bytes = "bors".bytes();
1152 ///
1153 /// assert_eq!(Some(b'b'), bytes.next());
1154 /// assert_eq!(Some(b'o'), bytes.next());
1155 /// assert_eq!(Some(b'r'), bytes.next());
1156 /// assert_eq!(Some(b's'), bytes.next());
1157 ///
1158 /// assert_eq!(None, bytes.next());
1159 /// ```
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 #[inline]
1162 #[ferrocene::prevalidated]
1163 pub fn bytes(&self) -> Bytes<'_> {
1164 Bytes(self.as_bytes().iter().copied())
1165 }
1166
1167 /// Splits a string slice by whitespace.
1168 ///
1169 /// The iterator returned will return string slices that are sub-slices of
1170 /// the original string slice, separated by any amount of whitespace.
1171 ///
1172 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1173 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
1174 /// instead, use [`split_ascii_whitespace`].
1175 ///
1176 /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
1177 ///
1178 /// # Examples
1179 ///
1180 /// Basic usage:
1181 ///
1182 /// ```
1183 /// let mut iter = "A few words".split_whitespace();
1184 ///
1185 /// assert_eq!(Some("A"), iter.next());
1186 /// assert_eq!(Some("few"), iter.next());
1187 /// assert_eq!(Some("words"), iter.next());
1188 ///
1189 /// assert_eq!(None, iter.next());
1190 /// ```
1191 ///
1192 /// All kinds of whitespace are considered:
1193 ///
1194 /// ```
1195 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
1196 /// assert_eq!(Some("Mary"), iter.next());
1197 /// assert_eq!(Some("had"), iter.next());
1198 /// assert_eq!(Some("a"), iter.next());
1199 /// assert_eq!(Some("little"), iter.next());
1200 /// assert_eq!(Some("lamb"), iter.next());
1201 ///
1202 /// assert_eq!(None, iter.next());
1203 /// ```
1204 ///
1205 /// If the string is empty or all whitespace, the iterator yields no string slices:
1206 /// ```
1207 /// assert_eq!("".split_whitespace().next(), None);
1208 /// assert_eq!(" ".split_whitespace().next(), None);
1209 /// ```
1210 #[must_use = "this returns the split string as an iterator, \
1211 without modifying the original"]
1212 #[stable(feature = "split_whitespace", since = "1.1.0")]
1213 #[rustc_diagnostic_item = "str_split_whitespace"]
1214 #[inline]
1215 pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
1216 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
1217 }
1218
1219 /// Splits a string slice by ASCII whitespace.
1220 ///
1221 /// The iterator returned will return string slices that are sub-slices of
1222 /// the original string slice, separated by any amount of ASCII whitespace.
1223 ///
1224 /// This uses the same definition as [`char::is_ascii_whitespace`].
1225 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
1226 ///
1227 /// [`split_whitespace`]: str::split_whitespace
1228 ///
1229 /// # Examples
1230 ///
1231 /// Basic usage:
1232 ///
1233 /// ```
1234 /// let mut iter = "A few words".split_ascii_whitespace();
1235 ///
1236 /// assert_eq!(Some("A"), iter.next());
1237 /// assert_eq!(Some("few"), iter.next());
1238 /// assert_eq!(Some("words"), iter.next());
1239 ///
1240 /// assert_eq!(None, iter.next());
1241 /// ```
1242 ///
1243 /// Various kinds of ASCII whitespace are considered
1244 /// (see [`char::is_ascii_whitespace`]):
1245 ///
1246 /// ```
1247 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
1248 /// assert_eq!(Some("Mary"), iter.next());
1249 /// assert_eq!(Some("had"), iter.next());
1250 /// assert_eq!(Some("a"), iter.next());
1251 /// assert_eq!(Some("little"), iter.next());
1252 /// assert_eq!(Some("lamb"), iter.next());
1253 ///
1254 /// assert_eq!(None, iter.next());
1255 /// ```
1256 ///
1257 /// If the string is empty or all ASCII whitespace, the iterator yields no string slices:
1258 /// ```
1259 /// assert_eq!("".split_ascii_whitespace().next(), None);
1260 /// assert_eq!(" ".split_ascii_whitespace().next(), None);
1261 /// ```
1262 #[must_use = "this returns the split string as an iterator, \
1263 without modifying the original"]
1264 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1265 #[inline]
1266 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
1267 let inner =
1268 self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
1269 SplitAsciiWhitespace { inner }
1270 }
1271
1272 /// Returns an iterator over the lines of a string, as string slices.
1273 ///
1274 /// Lines are split at line endings that are either newlines (`\n`) or
1275 /// sequences of a carriage return followed by a line feed (`\r\n`).
1276 ///
1277 /// Line terminators are not included in the lines returned by the iterator.
1278 ///
1279 /// Note that any carriage return (`\r`) not immediately followed by a
1280 /// line feed (`\n`) does not split a line. These carriage returns are
1281 /// thereby included in the produced lines.
1282 ///
1283 /// The final line ending is optional. A string that ends with a final line
1284 /// ending will return the same lines as an otherwise identical string
1285 /// without a final line ending.
1286 ///
1287 /// An empty string returns an empty iterator.
1288 ///
1289 /// # Examples
1290 ///
1291 /// Basic usage:
1292 ///
1293 /// ```
1294 /// let text = "foo\r\nbar\n\nbaz\r";
1295 /// let mut lines = text.lines();
1296 ///
1297 /// assert_eq!(Some("foo"), lines.next());
1298 /// assert_eq!(Some("bar"), lines.next());
1299 /// assert_eq!(Some(""), lines.next());
1300 /// // Trailing carriage return is included in the last line
1301 /// assert_eq!(Some("baz\r"), lines.next());
1302 ///
1303 /// assert_eq!(None, lines.next());
1304 /// ```
1305 ///
1306 /// The final line does not require any ending:
1307 ///
1308 /// ```
1309 /// let text = "foo\nbar\n\r\nbaz";
1310 /// let mut lines = text.lines();
1311 ///
1312 /// assert_eq!(Some("foo"), lines.next());
1313 /// assert_eq!(Some("bar"), lines.next());
1314 /// assert_eq!(Some(""), lines.next());
1315 /// assert_eq!(Some("baz"), lines.next());
1316 ///
1317 /// assert_eq!(None, lines.next());
1318 /// ```
1319 ///
1320 /// An empty string returns an empty iterator:
1321 ///
1322 /// ```
1323 /// let text = "";
1324 /// let mut lines = text.lines();
1325 ///
1326 /// assert_eq!(lines.next(), None);
1327 /// ```
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 #[inline]
1330 pub fn lines(&self) -> Lines<'_> {
1331 Lines(self.split_inclusive('\n').map(LinesMap))
1332 }
1333
1334 /// Returns an iterator over the lines of a string.
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 #[deprecated(since = "1.4.0", note = "use lines() instead now", suggestion = "lines")]
1337 #[inline]
1338 #[allow(deprecated)]
1339 pub fn lines_any(&self) -> LinesAny<'_> {
1340 LinesAny(self.lines())
1341 }
1342
1343 /// Returns an iterator of `u16` over the string encoded
1344 /// as native endian UTF-16 (without byte-order mark).
1345 ///
1346 /// # Examples
1347 ///
1348 /// ```
1349 /// let text = "Zażółć gęślą jaźń";
1350 ///
1351 /// let utf8_len = text.len();
1352 /// let utf16_len = text.encode_utf16().count();
1353 ///
1354 /// assert!(utf16_len <= utf8_len);
1355 /// ```
1356 #[must_use = "this returns the encoded string as an iterator, \
1357 without modifying the original"]
1358 #[stable(feature = "encode_utf16", since = "1.8.0")]
1359 pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
1360 EncodeUtf16 { chars: self.chars(), extra: 0 }
1361 }
1362
1363 /// Returns `true` if the given pattern matches a sub-slice of
1364 /// this string slice.
1365 ///
1366 /// Returns `false` if it does not.
1367 ///
1368 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1369 /// function or closure that determines if a character matches.
1370 ///
1371 /// [`char`]: prim@char
1372 /// [pattern]: self::pattern
1373 ///
1374 /// # Examples
1375 ///
1376 /// ```
1377 /// let bananas = "bananas";
1378 ///
1379 /// assert!(bananas.contains("nana"));
1380 /// assert!(!bananas.contains("apples"));
1381 /// ```
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 #[inline]
1384 pub fn contains<P: Pattern>(&self, pat: P) -> bool {
1385 pat.is_contained_in(self)
1386 }
1387
1388 /// Returns `true` if the given pattern matches a prefix of this
1389 /// string slice.
1390 ///
1391 /// Returns `false` if it does not.
1392 ///
1393 /// The [pattern] can be a `&str`, in which case this function will return true if
1394 /// the `&str` is a prefix of this string slice.
1395 ///
1396 /// The [pattern] can also be a [`char`], a slice of [`char`]s, or a
1397 /// function or closure that determines if a character matches.
1398 /// These will only be checked against the first character of this string slice.
1399 /// Look at the second example below regarding behavior for slices of [`char`]s.
1400 ///
1401 /// [`char`]: prim@char
1402 /// [pattern]: self::pattern
1403 ///
1404 /// # Examples
1405 ///
1406 /// ```
1407 /// let bananas = "bananas";
1408 ///
1409 /// assert!(bananas.starts_with("bana"));
1410 /// assert!(!bananas.starts_with("nana"));
1411 /// ```
1412 ///
1413 /// ```
1414 /// let bananas = "bananas";
1415 ///
1416 /// // Note that both of these assert successfully.
1417 /// assert!(bananas.starts_with(&['b', 'a', 'n', 'a']));
1418 /// assert!(bananas.starts_with(&['a', 'b', 'c', 'd']));
1419 /// ```
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 #[rustc_diagnostic_item = "str_starts_with"]
1422 #[ferrocene::prevalidated]
1423 pub fn starts_with<P: Pattern>(&self, pat: P) -> bool {
1424 pat.is_prefix_of(self)
1425 }
1426
1427 /// Returns `true` if the given pattern matches a suffix of this
1428 /// string slice.
1429 ///
1430 /// Returns `false` if it does not.
1431 ///
1432 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1433 /// function or closure that determines if a character matches.
1434 ///
1435 /// [`char`]: prim@char
1436 /// [pattern]: self::pattern
1437 ///
1438 /// # Examples
1439 ///
1440 /// ```
1441 /// let bananas = "bananas";
1442 ///
1443 /// assert!(bananas.ends_with("anas"));
1444 /// assert!(!bananas.ends_with("nana"));
1445 /// ```
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 #[rustc_diagnostic_item = "str_ends_with"]
1448 #[ferrocene::prevalidated]
1449 pub fn ends_with<P: Pattern>(&self, pat: P) -> bool
1450 where
1451 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1452 {
1453 pat.is_suffix_of(self)
1454 }
1455
1456 /// Returns the byte index of the first character of this string slice that
1457 /// matches the pattern.
1458 ///
1459 /// Returns [`None`] if the pattern doesn't match.
1460 ///
1461 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1462 /// function or closure that determines if a character matches.
1463 ///
1464 /// [`char`]: prim@char
1465 /// [pattern]: self::pattern
1466 ///
1467 /// # Examples
1468 ///
1469 /// Simple patterns:
1470 ///
1471 /// ```
1472 /// let s = "Löwe 老虎 Léopard Gepardi";
1473 ///
1474 /// assert_eq!(s.find('L'), Some(0));
1475 /// assert_eq!(s.find('é'), Some(14));
1476 /// assert_eq!(s.find("pard"), Some(17));
1477 /// ```
1478 ///
1479 /// More complex patterns using point-free style and closures:
1480 ///
1481 /// ```
1482 /// let s = "Löwe 老虎 Léopard";
1483 ///
1484 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1485 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1486 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1487 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1488 /// ```
1489 ///
1490 /// Not finding the pattern:
1491 ///
1492 /// ```
1493 /// let s = "Löwe 老虎 Léopard";
1494 /// let x: &[_] = &['1', '2'];
1495 ///
1496 /// assert_eq!(s.find(x), None);
1497 /// ```
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 #[inline]
1500 #[ferrocene::prevalidated]
1501 pub fn find<P: Pattern>(&self, pat: P) -> Option<usize> {
1502 pat.into_searcher(self).next_match().map(|(i, _)| i)
1503 }
1504
1505 /// Returns the byte index for the first character of the last match of the pattern in
1506 /// this string slice.
1507 ///
1508 /// Returns [`None`] if the pattern doesn't match.
1509 ///
1510 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1511 /// function or closure that determines if a character matches.
1512 ///
1513 /// [`char`]: prim@char
1514 /// [pattern]: self::pattern
1515 ///
1516 /// # Examples
1517 ///
1518 /// Simple patterns:
1519 ///
1520 /// ```
1521 /// let s = "Löwe 老虎 Léopard Gepardi";
1522 ///
1523 /// assert_eq!(s.rfind('L'), Some(13));
1524 /// assert_eq!(s.rfind('é'), Some(14));
1525 /// assert_eq!(s.rfind("pard"), Some(24));
1526 /// ```
1527 ///
1528 /// More complex patterns with closures:
1529 ///
1530 /// ```
1531 /// let s = "Löwe 老虎 Léopard";
1532 ///
1533 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1534 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1535 /// ```
1536 ///
1537 /// Not finding the pattern:
1538 ///
1539 /// ```
1540 /// let s = "Löwe 老虎 Léopard";
1541 /// let x: &[_] = &['1', '2'];
1542 ///
1543 /// assert_eq!(s.rfind(x), None);
1544 /// ```
1545 #[stable(feature = "rust1", since = "1.0.0")]
1546 #[inline]
1547 pub fn rfind<P: Pattern>(&self, pat: P) -> Option<usize>
1548 where
1549 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1550 {
1551 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1552 }
1553
1554 /// Returns an iterator over substrings of this string slice, separated by
1555 /// characters matched by a pattern.
1556 ///
1557 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1558 /// function or closure that determines if a character matches.
1559 ///
1560 /// If there are no matches the full string slice is returned as the only
1561 /// item in the iterator.
1562 ///
1563 /// [`char`]: prim@char
1564 /// [pattern]: self::pattern
1565 ///
1566 /// # Iterator behavior
1567 ///
1568 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1569 /// allows a reverse search and forward/reverse search yields the same
1570 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1571 ///
1572 /// If the pattern allows a reverse search but its results might differ
1573 /// from a forward search, the [`rsplit`] method can be used.
1574 ///
1575 /// [`rsplit`]: str::rsplit
1576 ///
1577 /// # Examples
1578 ///
1579 /// Simple patterns:
1580 ///
1581 /// ```
1582 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1583 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1584 ///
1585 /// let v: Vec<&str> = "".split('X').collect();
1586 /// assert_eq!(v, [""]);
1587 ///
1588 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1589 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1590 ///
1591 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1592 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1593 ///
1594 /// let v: Vec<&str> = "AABBCC".split("DD").collect();
1595 /// assert_eq!(v, ["AABBCC"]);
1596 ///
1597 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1598 /// assert_eq!(v, ["abc", "def", "ghi"]);
1599 ///
1600 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1601 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1602 /// ```
1603 ///
1604 /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1605 ///
1606 /// ```
1607 /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1608 /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1609 /// ```
1610 ///
1611 /// A more complex pattern, using a closure:
1612 ///
1613 /// ```
1614 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1615 /// assert_eq!(v, ["abc", "def", "ghi"]);
1616 /// ```
1617 ///
1618 /// If a string contains multiple contiguous separators, you will end up
1619 /// with empty strings in the output:
1620 ///
1621 /// ```
1622 /// let x = "||||a||b|c".to_string();
1623 /// let d: Vec<_> = x.split('|').collect();
1624 ///
1625 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1626 /// ```
1627 ///
1628 /// Contiguous separators are separated by the empty string.
1629 ///
1630 /// ```
1631 /// let x = "(///)".to_string();
1632 /// let d: Vec<_> = x.split('/').collect();
1633 ///
1634 /// assert_eq!(d, &["(", "", "", ")"]);
1635 /// ```
1636 ///
1637 /// Separators at the start or end of a string are neighbored
1638 /// by empty strings.
1639 ///
1640 /// ```
1641 /// let d: Vec<_> = "010".split("0").collect();
1642 /// assert_eq!(d, &["", "1", ""]);
1643 /// ```
1644 ///
1645 /// When the empty string is used as a separator, it separates
1646 /// every character in the string, along with the beginning
1647 /// and end of the string.
1648 ///
1649 /// ```
1650 /// let f: Vec<_> = "rust".split("").collect();
1651 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1652 /// ```
1653 ///
1654 /// Contiguous separators can lead to possibly surprising behavior
1655 /// when whitespace is used as the separator. This code is correct:
1656 ///
1657 /// ```
1658 /// let x = " a b c".to_string();
1659 /// let d: Vec<_> = x.split(' ').collect();
1660 ///
1661 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1662 /// ```
1663 ///
1664 /// It does _not_ give you:
1665 ///
1666 /// ```,ignore
1667 /// assert_eq!(d, &["a", "b", "c"]);
1668 /// ```
1669 ///
1670 /// Use [`split_whitespace`] for this behavior.
1671 ///
1672 /// [`split_whitespace`]: str::split_whitespace
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 #[inline]
1675 pub fn split<P: Pattern>(&self, pat: P) -> Split<'_, P> {
1676 Split(SplitInternal {
1677 start: 0,
1678 end: self.len(),
1679 matcher: pat.into_searcher(self),
1680 allow_trailing_empty: true,
1681 finished: false,
1682 })
1683 }
1684
1685 /// Returns an iterator over substrings of this string slice, separated by
1686 /// characters matched by a pattern.
1687 ///
1688 /// Differs from the iterator produced by `split` in that `split_inclusive`
1689 /// leaves the matched part as the terminator of the substring.
1690 ///
1691 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1692 /// function or closure that determines if a character matches.
1693 ///
1694 /// [`char`]: prim@char
1695 /// [pattern]: self::pattern
1696 ///
1697 /// # Examples
1698 ///
1699 /// ```
1700 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1701 /// .split_inclusive('\n').collect();
1702 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1703 /// ```
1704 ///
1705 /// If the last element of the string is matched,
1706 /// that element will be considered the terminator of the preceding substring.
1707 /// That substring will be the last item returned by the iterator.
1708 ///
1709 /// ```
1710 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1711 /// .split_inclusive('\n').collect();
1712 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1713 /// ```
1714 #[stable(feature = "split_inclusive", since = "1.51.0")]
1715 #[inline]
1716 #[ferrocene::prevalidated]
1717 pub fn split_inclusive<P: Pattern>(&self, pat: P) -> SplitInclusive<'_, P> {
1718 SplitInclusive(SplitInternal {
1719 start: 0,
1720 end: self.len(),
1721 matcher: pat.into_searcher(self),
1722 allow_trailing_empty: false,
1723 finished: false,
1724 })
1725 }
1726
1727 /// Returns an iterator over substrings of the given string slice, separated
1728 /// by characters matched by a pattern and yielded in reverse order.
1729 ///
1730 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1731 /// function or closure that determines if a character matches.
1732 ///
1733 /// [`char`]: prim@char
1734 /// [pattern]: self::pattern
1735 ///
1736 /// # Iterator behavior
1737 ///
1738 /// The returned iterator requires that the pattern supports a reverse
1739 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1740 /// search yields the same elements.
1741 ///
1742 /// For iterating from the front, the [`split`] method can be used.
1743 ///
1744 /// [`split`]: str::split
1745 ///
1746 /// # Examples
1747 ///
1748 /// Simple patterns:
1749 ///
1750 /// ```
1751 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1752 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1753 ///
1754 /// let v: Vec<&str> = "".rsplit('X').collect();
1755 /// assert_eq!(v, [""]);
1756 ///
1757 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1758 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1759 ///
1760 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1761 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1762 /// ```
1763 ///
1764 /// A more complex pattern, using a closure:
1765 ///
1766 /// ```
1767 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1768 /// assert_eq!(v, ["ghi", "def", "abc"]);
1769 /// ```
1770 #[stable(feature = "rust1", since = "1.0.0")]
1771 #[inline]
1772 pub fn rsplit<P: Pattern>(&self, pat: P) -> RSplit<'_, P>
1773 where
1774 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1775 {
1776 RSplit(self.split(pat).0)
1777 }
1778
1779 /// Returns an iterator over substrings of the given string slice, separated
1780 /// by characters matched by a pattern.
1781 ///
1782 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1783 /// function or closure that determines if a character matches.
1784 ///
1785 /// [`char`]: prim@char
1786 /// [pattern]: self::pattern
1787 ///
1788 /// Equivalent to [`split`], except that the trailing substring
1789 /// is skipped if empty.
1790 ///
1791 /// [`split`]: str::split
1792 ///
1793 /// This method can be used for string data that is _terminated_,
1794 /// rather than _separated_ by a pattern.
1795 ///
1796 /// # Iterator behavior
1797 ///
1798 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1799 /// allows a reverse search and forward/reverse search yields the same
1800 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1801 ///
1802 /// If the pattern allows a reverse search but its results might differ
1803 /// from a forward search, the [`rsplit_terminator`] method can be used.
1804 ///
1805 /// [`rsplit_terminator`]: str::rsplit_terminator
1806 ///
1807 /// # Examples
1808 ///
1809 /// ```
1810 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1811 /// assert_eq!(v, ["A", "B"]);
1812 ///
1813 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1814 /// assert_eq!(v, ["A", "", "B", ""]);
1815 ///
1816 /// let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
1817 /// assert_eq!(v, ["A", "B", "C", "D"]);
1818 /// ```
1819 #[stable(feature = "rust1", since = "1.0.0")]
1820 #[inline]
1821 pub fn split_terminator<P: Pattern>(&self, pat: P) -> SplitTerminator<'_, P> {
1822 SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1823 }
1824
1825 /// Returns an iterator over substrings of `self`, separated by characters
1826 /// matched by a pattern and yielded in reverse order.
1827 ///
1828 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1829 /// function or closure that determines if a character matches.
1830 ///
1831 /// [`char`]: prim@char
1832 /// [pattern]: self::pattern
1833 ///
1834 /// Equivalent to [`split`], except that the trailing substring is
1835 /// skipped if empty.
1836 ///
1837 /// [`split`]: str::split
1838 ///
1839 /// This method can be used for string data that is _terminated_,
1840 /// rather than _separated_ by a pattern.
1841 ///
1842 /// # Iterator behavior
1843 ///
1844 /// The returned iterator requires that the pattern supports a
1845 /// reverse search, and it will be double ended if a forward/reverse
1846 /// search yields the same elements.
1847 ///
1848 /// For iterating from the front, the [`split_terminator`] method can be
1849 /// used.
1850 ///
1851 /// [`split_terminator`]: str::split_terminator
1852 ///
1853 /// # Examples
1854 ///
1855 /// ```
1856 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1857 /// assert_eq!(v, ["B", "A"]);
1858 ///
1859 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1860 /// assert_eq!(v, ["", "B", "", "A"]);
1861 ///
1862 /// let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
1863 /// assert_eq!(v, ["D", "C", "B", "A"]);
1864 /// ```
1865 #[stable(feature = "rust1", since = "1.0.0")]
1866 #[inline]
1867 pub fn rsplit_terminator<P: Pattern>(&self, pat: P) -> RSplitTerminator<'_, P>
1868 where
1869 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1870 {
1871 RSplitTerminator(self.split_terminator(pat).0)
1872 }
1873
1874 /// Returns an iterator over substrings of the given string slice, separated
1875 /// by a pattern, restricted to returning at most `n` items.
1876 ///
1877 /// If `n` substrings are returned, the last substring (the `n`th substring)
1878 /// will contain the remainder of the string.
1879 ///
1880 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1881 /// function or closure that determines if a character matches.
1882 ///
1883 /// [`char`]: prim@char
1884 /// [pattern]: self::pattern
1885 ///
1886 /// # Iterator behavior
1887 ///
1888 /// The returned iterator will not be double ended, because it is
1889 /// not efficient to support.
1890 ///
1891 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1892 /// used.
1893 ///
1894 /// [`rsplitn`]: str::rsplitn
1895 ///
1896 /// # Examples
1897 ///
1898 /// Simple patterns:
1899 ///
1900 /// ```
1901 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1902 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1903 ///
1904 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1905 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1906 ///
1907 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1908 /// assert_eq!(v, ["abcXdef"]);
1909 ///
1910 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1911 /// assert_eq!(v, [""]);
1912 /// ```
1913 ///
1914 /// A more complex pattern, using a closure:
1915 ///
1916 /// ```
1917 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1918 /// assert_eq!(v, ["abc", "defXghi"]);
1919 /// ```
1920 #[stable(feature = "rust1", since = "1.0.0")]
1921 #[inline]
1922 pub fn splitn<P: Pattern>(&self, n: usize, pat: P) -> SplitN<'_, P> {
1923 SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1924 }
1925
1926 /// Returns an iterator over substrings of this string slice, separated by a
1927 /// pattern, starting from the end of the string, restricted to returning at
1928 /// most `n` items.
1929 ///
1930 /// If `n` substrings are returned, the last substring (the `n`th substring)
1931 /// will contain the remainder of the string.
1932 ///
1933 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1934 /// function or closure that determines if a character matches.
1935 ///
1936 /// [`char`]: prim@char
1937 /// [pattern]: self::pattern
1938 ///
1939 /// # Iterator behavior
1940 ///
1941 /// The returned iterator will not be double ended, because it is not
1942 /// efficient to support.
1943 ///
1944 /// For splitting from the front, the [`splitn`] method can be used.
1945 ///
1946 /// [`splitn`]: str::splitn
1947 ///
1948 /// # Examples
1949 ///
1950 /// Simple patterns:
1951 ///
1952 /// ```
1953 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1954 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1955 ///
1956 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1957 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1958 ///
1959 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1960 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1961 /// ```
1962 ///
1963 /// A more complex pattern, using a closure:
1964 ///
1965 /// ```
1966 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1967 /// assert_eq!(v, ["ghi", "abc1def"]);
1968 /// ```
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 #[inline]
1971 pub fn rsplitn<P: Pattern>(&self, n: usize, pat: P) -> RSplitN<'_, P>
1972 where
1973 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1974 {
1975 RSplitN(self.splitn(n, pat).0)
1976 }
1977
1978 /// Splits the string on the first occurrence of the specified delimiter and
1979 /// returns prefix before delimiter and suffix after delimiter.
1980 ///
1981 /// # Examples
1982 ///
1983 /// ```
1984 /// assert_eq!("cfg".split_once('='), None);
1985 /// assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
1986 /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1987 /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1988 /// ```
1989 #[stable(feature = "str_split_once", since = "1.52.0")]
1990 #[inline]
1991 pub fn split_once<P: Pattern>(&self, delimiter: P) -> Option<(&'_ str, &'_ str)> {
1992 let (start, end) = delimiter.into_searcher(self).next_match()?;
1993 // SAFETY: `Searcher` is known to return valid indices.
1994 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1995 }
1996
1997 /// Splits the string on the last occurrence of the specified delimiter and
1998 /// returns prefix before delimiter and suffix after delimiter.
1999 ///
2000 /// # Examples
2001 ///
2002 /// ```
2003 /// assert_eq!("cfg".rsplit_once('='), None);
2004 /// assert_eq!("cfg=".rsplit_once('='), Some(("cfg", "")));
2005 /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
2006 /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
2007 /// ```
2008 #[stable(feature = "str_split_once", since = "1.52.0")]
2009 #[inline]
2010 pub fn rsplit_once<P: Pattern>(&self, delimiter: P) -> Option<(&'_ str, &'_ str)>
2011 where
2012 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2013 {
2014 let (start, end) = delimiter.into_searcher(self).next_match_back()?;
2015 // SAFETY: `Searcher` is known to return valid indices.
2016 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
2017 }
2018
2019 /// Returns an iterator over the disjoint matches of a pattern within the
2020 /// given string slice.
2021 ///
2022 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2023 /// function or closure that determines if a character matches.
2024 ///
2025 /// [`char`]: prim@char
2026 /// [pattern]: self::pattern
2027 ///
2028 /// # Iterator behavior
2029 ///
2030 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2031 /// allows a reverse search and forward/reverse search yields the same
2032 /// elements. This is true for, e.g., [`char`], but not for `&str`.
2033 ///
2034 /// If the pattern allows a reverse search but its results might differ
2035 /// from a forward search, the [`rmatches`] method can be used.
2036 ///
2037 /// [`rmatches`]: str::rmatches
2038 ///
2039 /// # Examples
2040 ///
2041 /// ```
2042 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
2043 /// assert_eq!(v, ["abc", "abc", "abc"]);
2044 ///
2045 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
2046 /// assert_eq!(v, ["1", "2", "3"]);
2047 /// ```
2048 #[stable(feature = "str_matches", since = "1.2.0")]
2049 #[inline]
2050 pub fn matches<P: Pattern>(&self, pat: P) -> Matches<'_, P> {
2051 Matches(MatchesInternal(pat.into_searcher(self)))
2052 }
2053
2054 /// Returns an iterator over the disjoint matches of a pattern within this
2055 /// string slice, yielded in reverse order.
2056 ///
2057 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2058 /// function or closure that determines if a character matches.
2059 ///
2060 /// [`char`]: prim@char
2061 /// [pattern]: self::pattern
2062 ///
2063 /// # Iterator behavior
2064 ///
2065 /// The returned iterator requires that the pattern supports a reverse
2066 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
2067 /// search yields the same elements.
2068 ///
2069 /// For iterating from the front, the [`matches`] method can be used.
2070 ///
2071 /// [`matches`]: str::matches
2072 ///
2073 /// # Examples
2074 ///
2075 /// ```
2076 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
2077 /// assert_eq!(v, ["abc", "abc", "abc"]);
2078 ///
2079 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
2080 /// assert_eq!(v, ["3", "2", "1"]);
2081 /// ```
2082 #[stable(feature = "str_matches", since = "1.2.0")]
2083 #[inline]
2084 pub fn rmatches<P: Pattern>(&self, pat: P) -> RMatches<'_, P>
2085 where
2086 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2087 {
2088 RMatches(self.matches(pat).0)
2089 }
2090
2091 /// Returns an iterator over the disjoint matches of a pattern within this string
2092 /// slice as well as the index that the match starts at.
2093 ///
2094 /// For matches of `pat` within `self` that overlap, only the indices
2095 /// corresponding to the first match are returned.
2096 ///
2097 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2098 /// function or closure that determines if a character matches.
2099 ///
2100 /// [`char`]: prim@char
2101 /// [pattern]: self::pattern
2102 ///
2103 /// # Iterator behavior
2104 ///
2105 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2106 /// allows a reverse search and forward/reverse search yields the same
2107 /// elements. This is true for, e.g., [`char`], but not for `&str`.
2108 ///
2109 /// If the pattern allows a reverse search but its results might differ
2110 /// from a forward search, the [`rmatch_indices`] method can be used.
2111 ///
2112 /// [`rmatch_indices`]: str::rmatch_indices
2113 ///
2114 /// # Examples
2115 ///
2116 /// ```
2117 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
2118 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
2119 ///
2120 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
2121 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
2122 ///
2123 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
2124 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
2125 /// ```
2126 #[stable(feature = "str_match_indices", since = "1.5.0")]
2127 #[inline]
2128 pub fn match_indices<P: Pattern>(&self, pat: P) -> MatchIndices<'_, P> {
2129 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
2130 }
2131
2132 /// Returns an iterator over the disjoint matches of a pattern within `self`,
2133 /// yielded in reverse order along with the index of the match.
2134 ///
2135 /// For matches of `pat` within `self` that overlap, only the indices
2136 /// corresponding to the last match are returned.
2137 ///
2138 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2139 /// function or closure that determines if a character matches.
2140 ///
2141 /// [`char`]: prim@char
2142 /// [pattern]: self::pattern
2143 ///
2144 /// # Iterator behavior
2145 ///
2146 /// The returned iterator requires that the pattern supports a reverse
2147 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
2148 /// search yields the same elements.
2149 ///
2150 /// For iterating from the front, the [`match_indices`] method can be used.
2151 ///
2152 /// [`match_indices`]: str::match_indices
2153 ///
2154 /// # Examples
2155 ///
2156 /// ```
2157 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
2158 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
2159 ///
2160 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
2161 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
2162 ///
2163 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
2164 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
2165 /// ```
2166 #[stable(feature = "str_match_indices", since = "1.5.0")]
2167 #[inline]
2168 pub fn rmatch_indices<P: Pattern>(&self, pat: P) -> RMatchIndices<'_, P>
2169 where
2170 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2171 {
2172 RMatchIndices(self.match_indices(pat).0)
2173 }
2174
2175 /// Returns a string slice with leading and trailing whitespace removed.
2176 ///
2177 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2178 /// Core Property `White_Space`, which includes newlines.
2179 ///
2180 /// # Examples
2181 ///
2182 /// ```
2183 /// let s = "\n Hello\tworld\t\n";
2184 ///
2185 /// assert_eq!("Hello\tworld", s.trim());
2186 /// ```
2187 #[inline]
2188 #[must_use = "this returns the trimmed string as a slice, \
2189 without modifying the original"]
2190 #[stable(feature = "rust1", since = "1.0.0")]
2191 #[rustc_diagnostic_item = "str_trim"]
2192 pub fn trim(&self) -> &str {
2193 self.trim_matches(char::is_whitespace)
2194 }
2195
2196 /// Returns a string slice with leading whitespace removed.
2197 ///
2198 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2199 /// Core Property `White_Space`, which includes newlines.
2200 ///
2201 /// # Text directionality
2202 ///
2203 /// A string is a sequence of bytes. `start` in this context means the first
2204 /// position of that byte string; for a left-to-right language like English or
2205 /// Russian, this will be left side, and for right-to-left languages like
2206 /// Arabic or Hebrew, this will be the right side.
2207 ///
2208 /// # Examples
2209 ///
2210 /// Basic usage:
2211 ///
2212 /// ```
2213 /// let s = "\n Hello\tworld\t\n";
2214 /// assert_eq!("Hello\tworld\t\n", s.trim_start());
2215 /// ```
2216 ///
2217 /// Directionality:
2218 ///
2219 /// ```
2220 /// let s = " English ";
2221 /// assert!(Some('E') == s.trim_start().chars().next());
2222 ///
2223 /// let s = " עברית ";
2224 /// assert!(Some('ע') == s.trim_start().chars().next());
2225 /// ```
2226 #[inline]
2227 #[must_use = "this returns the trimmed string as a new slice, \
2228 without modifying the original"]
2229 #[stable(feature = "trim_direction", since = "1.30.0")]
2230 #[rustc_diagnostic_item = "str_trim_start"]
2231 pub fn trim_start(&self) -> &str {
2232 self.trim_start_matches(char::is_whitespace)
2233 }
2234
2235 /// Returns a string slice with trailing whitespace removed.
2236 ///
2237 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2238 /// Core Property `White_Space`, which includes newlines.
2239 ///
2240 /// # Text directionality
2241 ///
2242 /// A string is a sequence of bytes. `end` in this context means the last
2243 /// position of that byte string; for a left-to-right language like English or
2244 /// Russian, this will be right side, and for right-to-left languages like
2245 /// Arabic or Hebrew, this will be the left side.
2246 ///
2247 /// # Examples
2248 ///
2249 /// Basic usage:
2250 ///
2251 /// ```
2252 /// let s = "\n Hello\tworld\t\n";
2253 /// assert_eq!("\n Hello\tworld", s.trim_end());
2254 /// ```
2255 ///
2256 /// Directionality:
2257 ///
2258 /// ```
2259 /// let s = " English ";
2260 /// assert!(Some('h') == s.trim_end().chars().rev().next());
2261 ///
2262 /// let s = " עברית ";
2263 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
2264 /// ```
2265 #[inline]
2266 #[must_use = "this returns the trimmed string as a new slice, \
2267 without modifying the original"]
2268 #[stable(feature = "trim_direction", since = "1.30.0")]
2269 #[rustc_diagnostic_item = "str_trim_end"]
2270 pub fn trim_end(&self) -> &str {
2271 self.trim_end_matches(char::is_whitespace)
2272 }
2273
2274 /// Returns a string slice with leading whitespace removed.
2275 ///
2276 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2277 /// Core Property `White_Space`.
2278 ///
2279 /// # Text directionality
2280 ///
2281 /// A string is a sequence of bytes. 'Left' in this context means the first
2282 /// position of that byte string; for a language like Arabic or Hebrew
2283 /// which are 'right to left' rather than 'left to right', this will be
2284 /// the _right_ side, not the left.
2285 ///
2286 /// # Examples
2287 ///
2288 /// Basic usage:
2289 ///
2290 /// ```
2291 /// let s = " Hello\tworld\t";
2292 ///
2293 /// assert_eq!("Hello\tworld\t", s.trim_left());
2294 /// ```
2295 ///
2296 /// Directionality:
2297 ///
2298 /// ```
2299 /// let s = " English";
2300 /// assert!(Some('E') == s.trim_left().chars().next());
2301 ///
2302 /// let s = " עברית";
2303 /// assert!(Some('ע') == s.trim_left().chars().next());
2304 /// ```
2305 #[must_use = "this returns the trimmed string as a new slice, \
2306 without modifying the original"]
2307 #[inline]
2308 #[stable(feature = "rust1", since = "1.0.0")]
2309 #[deprecated(since = "1.33.0", note = "superseded by `trim_start`", suggestion = "trim_start")]
2310 pub fn trim_left(&self) -> &str {
2311 self.trim_start()
2312 }
2313
2314 /// Returns a string slice with trailing whitespace removed.
2315 ///
2316 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2317 /// Core Property `White_Space`.
2318 ///
2319 /// # Text directionality
2320 ///
2321 /// A string is a sequence of bytes. 'Right' in this context means the last
2322 /// position of that byte string; for a language like Arabic or Hebrew
2323 /// which are 'right to left' rather than 'left to right', this will be
2324 /// the _left_ side, not the right.
2325 ///
2326 /// # Examples
2327 ///
2328 /// Basic usage:
2329 ///
2330 /// ```
2331 /// let s = " Hello\tworld\t";
2332 ///
2333 /// assert_eq!(" Hello\tworld", s.trim_right());
2334 /// ```
2335 ///
2336 /// Directionality:
2337 ///
2338 /// ```
2339 /// let s = "English ";
2340 /// assert!(Some('h') == s.trim_right().chars().rev().next());
2341 ///
2342 /// let s = "עברית ";
2343 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
2344 /// ```
2345 #[must_use = "this returns the trimmed string as a new slice, \
2346 without modifying the original"]
2347 #[inline]
2348 #[stable(feature = "rust1", since = "1.0.0")]
2349 #[deprecated(since = "1.33.0", note = "superseded by `trim_end`", suggestion = "trim_end")]
2350 pub fn trim_right(&self) -> &str {
2351 self.trim_end()
2352 }
2353
2354 /// Returns a string slice with all prefixes and suffixes that match a
2355 /// pattern repeatedly removed.
2356 ///
2357 /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
2358 /// or closure that determines if a character matches.
2359 ///
2360 /// [`char`]: prim@char
2361 /// [pattern]: self::pattern
2362 ///
2363 /// # Examples
2364 ///
2365 /// Simple patterns:
2366 ///
2367 /// ```
2368 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
2369 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
2370 ///
2371 /// let x: &[_] = &['1', '2'];
2372 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
2373 /// ```
2374 ///
2375 /// A more complex pattern, using a closure:
2376 ///
2377 /// ```
2378 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
2379 /// ```
2380 #[must_use = "this returns the trimmed string as a new slice, \
2381 without modifying the original"]
2382 #[stable(feature = "rust1", since = "1.0.0")]
2383 pub fn trim_matches<P: Pattern>(&self, pat: P) -> &str
2384 where
2385 for<'a> P::Searcher<'a>: DoubleEndedSearcher<'a>,
2386 {
2387 let mut i = 0;
2388 let mut j = 0;
2389 let mut matcher = pat.into_searcher(self);
2390 if let Some((a, b)) = matcher.next_reject() {
2391 i = a;
2392 j = b; // Remember earliest known match, correct it below if
2393 // last match is different
2394 }
2395 if let Some((_, b)) = matcher.next_reject_back() {
2396 j = b;
2397 }
2398 // SAFETY: `Searcher` is known to return valid indices.
2399 unsafe { self.get_unchecked(i..j) }
2400 }
2401
2402 /// Returns a string slice with all prefixes that match a pattern
2403 /// repeatedly removed.
2404 ///
2405 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2406 /// function or closure that determines if a character matches.
2407 ///
2408 /// [`char`]: prim@char
2409 /// [pattern]: self::pattern
2410 ///
2411 /// # Text directionality
2412 ///
2413 /// A string is a sequence of bytes. `start` in this context means the first
2414 /// position of that byte string; for a left-to-right language like English or
2415 /// Russian, this will be left side, and for right-to-left languages like
2416 /// Arabic or Hebrew, this will be the right side.
2417 ///
2418 /// # Examples
2419 ///
2420 /// ```
2421 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
2422 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
2423 ///
2424 /// let x: &[_] = &['1', '2'];
2425 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
2426 /// ```
2427 #[must_use = "this returns the trimmed string as a new slice, \
2428 without modifying the original"]
2429 #[stable(feature = "trim_direction", since = "1.30.0")]
2430 pub fn trim_start_matches<P: Pattern>(&self, pat: P) -> &str {
2431 let mut i = self.len();
2432 let mut matcher = pat.into_searcher(self);
2433 if let Some((a, _)) = matcher.next_reject() {
2434 i = a;
2435 }
2436 // SAFETY: `Searcher` is known to return valid indices.
2437 unsafe { self.get_unchecked(i..self.len()) }
2438 }
2439
2440 /// Returns a string slice with the prefix removed.
2441 ///
2442 /// If the string starts with the pattern `prefix`, returns the substring after the prefix,
2443 /// wrapped in `Some`. Unlike [`trim_start_matches`], this method removes the prefix exactly once.
2444 ///
2445 /// If the string does not start with `prefix`, returns `None`.
2446 ///
2447 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2448 /// function or closure that determines if a character matches.
2449 ///
2450 /// [`char`]: prim@char
2451 /// [pattern]: self::pattern
2452 /// [`trim_start_matches`]: Self::trim_start_matches
2453 ///
2454 /// # Examples
2455 ///
2456 /// ```
2457 /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2458 /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2459 /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2460 /// ```
2461 #[must_use = "this returns the remaining substring as a new slice, \
2462 without modifying the original"]
2463 #[stable(feature = "str_strip", since = "1.45.0")]
2464 pub fn strip_prefix<P: Pattern>(&self, prefix: P) -> Option<&str> {
2465 prefix.strip_prefix_of(self)
2466 }
2467
2468 /// Returns a string slice with the suffix removed.
2469 ///
2470 /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2471 /// wrapped in `Some`. Unlike [`trim_end_matches`], this method removes the suffix exactly once.
2472 ///
2473 /// If the string does not end with `suffix`, returns `None`.
2474 ///
2475 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2476 /// function or closure that determines if a character matches.
2477 ///
2478 /// [`char`]: prim@char
2479 /// [pattern]: self::pattern
2480 /// [`trim_end_matches`]: Self::trim_end_matches
2481 ///
2482 /// # Examples
2483 ///
2484 /// ```
2485 /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2486 /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2487 /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2488 /// ```
2489 #[must_use = "this returns the remaining substring as a new slice, \
2490 without modifying the original"]
2491 #[stable(feature = "str_strip", since = "1.45.0")]
2492 pub fn strip_suffix<P: Pattern>(&self, suffix: P) -> Option<&str>
2493 where
2494 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2495 {
2496 suffix.strip_suffix_of(self)
2497 }
2498
2499 /// Returns a string slice with the prefix and suffix removed.
2500 ///
2501 /// If the string starts with the pattern `prefix` and ends with the pattern `suffix`, returns
2502 /// the substring after the prefix and before the suffix, wrapped in `Some`.
2503 /// Unlike [`trim_start_matches`] and [`trim_end_matches`], this method removes both the prefix
2504 /// and suffix exactly once.
2505 ///
2506 /// If the string does not start with `prefix` or does not end with `suffix`, returns `None`.
2507 ///
2508 /// Each [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2509 /// function or closure that determines if a character matches.
2510 ///
2511 /// [`char`]: prim@char
2512 /// [pattern]: self::pattern
2513 /// [`trim_start_matches`]: Self::trim_start_matches
2514 /// [`trim_end_matches`]: Self::trim_end_matches
2515 ///
2516 /// # Examples
2517 ///
2518 /// ```
2519 /// #![feature(strip_circumfix)]
2520 ///
2521 /// assert_eq!("bar:hello:foo".strip_circumfix("bar:", ":foo"), Some("hello"));
2522 /// assert_eq!("bar:foo".strip_circumfix("foo", "foo"), None);
2523 /// assert_eq!("foo:bar;".strip_circumfix("foo:", ';'), Some("bar"));
2524 /// ```
2525 #[must_use = "this returns the remaining substring as a new slice, \
2526 without modifying the original"]
2527 #[unstable(feature = "strip_circumfix", issue = "147946")]
2528 pub fn strip_circumfix<P: Pattern, S: Pattern>(&self, prefix: P, suffix: S) -> Option<&str>
2529 where
2530 for<'a> S::Searcher<'a>: ReverseSearcher<'a>,
2531 {
2532 self.strip_prefix(prefix)?.strip_suffix(suffix)
2533 }
2534
2535 /// Returns a string slice with the optional prefix removed.
2536 ///
2537 /// If the string starts with the pattern `prefix`, returns the substring after the prefix.
2538 /// Unlike [`strip_prefix`], this method always returns `&str` for easy method chaining,
2539 /// instead of returning [`Option<&str>`].
2540 ///
2541 /// If the string does not start with `prefix`, returns the original string unchanged.
2542 ///
2543 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2544 /// function or closure that determines if a character matches.
2545 ///
2546 /// [`char`]: prim@char
2547 /// [pattern]: self::pattern
2548 /// [`strip_prefix`]: Self::strip_prefix
2549 ///
2550 /// # Examples
2551 ///
2552 /// ```
2553 /// #![feature(trim_prefix_suffix)]
2554 ///
2555 /// // Prefix present - removes it
2556 /// assert_eq!("foo:bar".trim_prefix("foo:"), "bar");
2557 /// assert_eq!("foofoo".trim_prefix("foo"), "foo");
2558 ///
2559 /// // Prefix absent - returns original string
2560 /// assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar");
2561 ///
2562 /// // Method chaining example
2563 /// assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
2564 /// ```
2565 #[must_use = "this returns the remaining substring as a new slice, \
2566 without modifying the original"]
2567 #[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2568 pub fn trim_prefix<P: Pattern>(&self, prefix: P) -> &str {
2569 prefix.strip_prefix_of(self).unwrap_or(self)
2570 }
2571
2572 /// Returns a string slice with the optional suffix removed.
2573 ///
2574 /// If the string ends with the pattern `suffix`, returns the substring before the suffix.
2575 /// Unlike [`strip_suffix`], this method always returns `&str` for easy method chaining,
2576 /// instead of returning [`Option<&str>`].
2577 ///
2578 /// If the string does not end with `suffix`, returns the original string unchanged.
2579 ///
2580 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2581 /// function or closure that determines if a character matches.
2582 ///
2583 /// [`char`]: prim@char
2584 /// [pattern]: self::pattern
2585 /// [`strip_suffix`]: Self::strip_suffix
2586 ///
2587 /// # Examples
2588 ///
2589 /// ```
2590 /// #![feature(trim_prefix_suffix)]
2591 ///
2592 /// // Suffix present - removes it
2593 /// assert_eq!("bar:foo".trim_suffix(":foo"), "bar");
2594 /// assert_eq!("foofoo".trim_suffix("foo"), "foo");
2595 ///
2596 /// // Suffix absent - returns original string
2597 /// assert_eq!("bar:foo".trim_suffix("bar"), "bar:foo");
2598 ///
2599 /// // Method chaining example
2600 /// assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
2601 /// ```
2602 #[must_use = "this returns the remaining substring as a new slice, \
2603 without modifying the original"]
2604 #[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2605 pub fn trim_suffix<P: Pattern>(&self, suffix: P) -> &str
2606 where
2607 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2608 {
2609 suffix.strip_suffix_of(self).unwrap_or(self)
2610 }
2611
2612 /// Returns a string slice with all suffixes that match a pattern
2613 /// repeatedly removed.
2614 ///
2615 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2616 /// function or closure that determines if a character matches.
2617 ///
2618 /// [`char`]: prim@char
2619 /// [pattern]: self::pattern
2620 ///
2621 /// # Text directionality
2622 ///
2623 /// A string is a sequence of bytes. `end` in this context means the last
2624 /// position of that byte string; for a left-to-right language like English or
2625 /// Russian, this will be right side, and for right-to-left languages like
2626 /// Arabic or Hebrew, this will be the left side.
2627 ///
2628 /// # Examples
2629 ///
2630 /// Simple patterns:
2631 ///
2632 /// ```
2633 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2634 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2635 ///
2636 /// let x: &[_] = &['1', '2'];
2637 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2638 /// ```
2639 ///
2640 /// A more complex pattern, using a closure:
2641 ///
2642 /// ```
2643 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2644 /// ```
2645 #[must_use = "this returns the trimmed string as a new slice, \
2646 without modifying the original"]
2647 #[stable(feature = "trim_direction", since = "1.30.0")]
2648 pub fn trim_end_matches<P: Pattern>(&self, pat: P) -> &str
2649 where
2650 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2651 {
2652 let mut j = 0;
2653 let mut matcher = pat.into_searcher(self);
2654 if let Some((_, b)) = matcher.next_reject_back() {
2655 j = b;
2656 }
2657 // SAFETY: `Searcher` is known to return valid indices.
2658 unsafe { self.get_unchecked(0..j) }
2659 }
2660
2661 /// Returns a string slice with all prefixes that match a pattern
2662 /// repeatedly removed.
2663 ///
2664 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2665 /// function or closure that determines if a character matches.
2666 ///
2667 /// [`char`]: prim@char
2668 /// [pattern]: self::pattern
2669 ///
2670 /// # Text directionality
2671 ///
2672 /// A string is a sequence of bytes. 'Left' in this context means the first
2673 /// position of that byte string; for a language like Arabic or Hebrew
2674 /// which are 'right to left' rather than 'left to right', this will be
2675 /// the _right_ side, not the left.
2676 ///
2677 /// # Examples
2678 ///
2679 /// ```
2680 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2681 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2682 ///
2683 /// let x: &[_] = &['1', '2'];
2684 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2685 /// ```
2686 #[stable(feature = "rust1", since = "1.0.0")]
2687 #[deprecated(
2688 since = "1.33.0",
2689 note = "superseded by `trim_start_matches`",
2690 suggestion = "trim_start_matches"
2691 )]
2692 pub fn trim_left_matches<P: Pattern>(&self, pat: P) -> &str {
2693 self.trim_start_matches(pat)
2694 }
2695
2696 /// Returns a string slice with all suffixes that match a pattern
2697 /// repeatedly removed.
2698 ///
2699 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2700 /// function or closure that determines if a character matches.
2701 ///
2702 /// [`char`]: prim@char
2703 /// [pattern]: self::pattern
2704 ///
2705 /// # Text directionality
2706 ///
2707 /// A string is a sequence of bytes. 'Right' in this context means the last
2708 /// position of that byte string; for a language like Arabic or Hebrew
2709 /// which are 'right to left' rather than 'left to right', this will be
2710 /// the _left_ side, not the right.
2711 ///
2712 /// # Examples
2713 ///
2714 /// Simple patterns:
2715 ///
2716 /// ```
2717 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2718 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2719 ///
2720 /// let x: &[_] = &['1', '2'];
2721 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2722 /// ```
2723 ///
2724 /// A more complex pattern, using a closure:
2725 ///
2726 /// ```
2727 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2728 /// ```
2729 #[stable(feature = "rust1", since = "1.0.0")]
2730 #[deprecated(
2731 since = "1.33.0",
2732 note = "superseded by `trim_end_matches`",
2733 suggestion = "trim_end_matches"
2734 )]
2735 pub fn trim_right_matches<P: Pattern>(&self, pat: P) -> &str
2736 where
2737 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2738 {
2739 self.trim_end_matches(pat)
2740 }
2741
2742 /// Parses this string slice into another type.
2743 ///
2744 /// Because `parse` is so general, it can cause problems with type
2745 /// inference. As such, `parse` is one of the few times you'll see
2746 /// the syntax affectionately known as the 'turbofish': `::<>`. This
2747 /// helps the inference algorithm understand specifically which type
2748 /// you're trying to parse into.
2749 ///
2750 /// `parse` can parse into any type that implements the [`FromStr`] trait.
2751 ///
2752 /// # Errors
2753 ///
2754 /// Will return [`Err`] if it's not possible to parse this string slice into
2755 /// the desired type.
2756 ///
2757 /// [`Err`]: FromStr::Err
2758 ///
2759 /// # Examples
2760 ///
2761 /// Basic usage:
2762 ///
2763 /// ```
2764 /// let four: u32 = "4".parse().unwrap();
2765 ///
2766 /// assert_eq!(4, four);
2767 /// ```
2768 ///
2769 /// Using the 'turbofish' instead of annotating `four`:
2770 ///
2771 /// ```
2772 /// let four = "4".parse::<u32>();
2773 ///
2774 /// assert_eq!(Ok(4), four);
2775 /// ```
2776 ///
2777 /// Failing to parse:
2778 ///
2779 /// ```
2780 /// let nope = "j".parse::<u32>();
2781 ///
2782 /// assert!(nope.is_err());
2783 /// ```
2784 #[inline]
2785 #[stable(feature = "rust1", since = "1.0.0")]
2786 #[ferrocene::prevalidated]
2787 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2788 FromStr::from_str(self)
2789 }
2790
2791 /// Checks if all characters in this string are within the ASCII range.
2792 ///
2793 /// An empty string returns `true`.
2794 ///
2795 /// # Examples
2796 ///
2797 /// ```
2798 /// let ascii = "hello!\n";
2799 /// let non_ascii = "Grüße, Jürgen ❤";
2800 ///
2801 /// assert!(ascii.is_ascii());
2802 /// assert!(!non_ascii.is_ascii());
2803 /// ```
2804 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2805 #[rustc_const_stable(feature = "const_slice_is_ascii", since = "1.74.0")]
2806 #[must_use]
2807 #[inline]
2808 #[ferrocene::prevalidated]
2809 pub const fn is_ascii(&self) -> bool {
2810 // We can treat each byte as character here: all multibyte characters
2811 // start with a byte that is not in the ASCII range, so we will stop
2812 // there already.
2813 self.as_bytes().is_ascii()
2814 }
2815
2816 /// If this string slice [`is_ascii`](Self::is_ascii), returns it as a slice
2817 /// of [ASCII characters](`ascii::Char`), otherwise returns `None`.
2818 #[unstable(feature = "ascii_char", issue = "110998")]
2819 #[must_use]
2820 #[inline]
2821 pub const fn as_ascii(&self) -> Option<&[ascii::Char]> {
2822 // Like in `is_ascii`, we can work on the bytes directly.
2823 self.as_bytes().as_ascii()
2824 }
2825
2826 /// Converts this string slice into a slice of [ASCII characters](ascii::Char),
2827 /// without checking whether they are valid.
2828 ///
2829 /// # Safety
2830 ///
2831 /// Every character in this string must be ASCII, or else this is UB.
2832 #[unstable(feature = "ascii_char", issue = "110998")]
2833 #[must_use]
2834 #[inline]
2835 pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char] {
2836 assert_unsafe_precondition!(
2837 check_library_ub,
2838 "as_ascii_unchecked requires that the string is valid ASCII",
2839 (it: &str = self) => it.is_ascii()
2840 );
2841
2842 // SAFETY: the caller promised that every byte of this string slice
2843 // is ASCII.
2844 unsafe { self.as_bytes().as_ascii_unchecked() }
2845 }
2846
2847 /// Checks that two strings are an ASCII case-insensitive match.
2848 ///
2849 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2850 /// but without allocating and copying temporaries.
2851 ///
2852 /// # Examples
2853 ///
2854 /// ```
2855 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2856 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2857 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2858 /// ```
2859 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2860 #[rustc_const_stable(feature = "const_eq_ignore_ascii_case", since = "1.89.0")]
2861 #[must_use]
2862 #[inline]
2863 #[ferrocene::prevalidated]
2864 pub const fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2865 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2866 }
2867
2868 /// Converts this string to its ASCII upper case equivalent in-place.
2869 ///
2870 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2871 /// but non-ASCII letters are unchanged.
2872 ///
2873 /// To return a new uppercased value without modifying the existing one, use
2874 /// [`to_ascii_uppercase()`].
2875 ///
2876 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2877 ///
2878 /// # Examples
2879 ///
2880 /// ```
2881 /// let mut s = String::from("Grüße, Jürgen ❤");
2882 ///
2883 /// s.make_ascii_uppercase();
2884 ///
2885 /// assert_eq!("GRüßE, JüRGEN ❤", s);
2886 /// ```
2887 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2888 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2889 #[inline]
2890 pub const fn make_ascii_uppercase(&mut self) {
2891 // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2892 let me = unsafe { self.as_bytes_mut() };
2893 me.make_ascii_uppercase()
2894 }
2895
2896 /// Converts this string to its ASCII lower case equivalent in-place.
2897 ///
2898 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2899 /// but non-ASCII letters are unchanged.
2900 ///
2901 /// To return a new lowercased value without modifying the existing one, use
2902 /// [`to_ascii_lowercase()`].
2903 ///
2904 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2905 ///
2906 /// # Examples
2907 ///
2908 /// ```
2909 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2910 ///
2911 /// s.make_ascii_lowercase();
2912 ///
2913 /// assert_eq!("grÜße, jÜrgen ❤", s);
2914 /// ```
2915 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2916 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2917 #[inline]
2918 pub const fn make_ascii_lowercase(&mut self) {
2919 // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2920 let me = unsafe { self.as_bytes_mut() };
2921 me.make_ascii_lowercase()
2922 }
2923
2924 /// Returns a string slice with leading ASCII whitespace removed.
2925 ///
2926 /// 'Whitespace' refers to the definition used by
2927 /// [`u8::is_ascii_whitespace`].
2928 ///
2929 /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
2930 ///
2931 /// # Examples
2932 ///
2933 /// ```
2934 /// assert_eq!(" \t \u{3000}hello world\n".trim_ascii_start(), "\u{3000}hello world\n");
2935 /// assert_eq!(" ".trim_ascii_start(), "");
2936 /// assert_eq!("".trim_ascii_start(), "");
2937 /// ```
2938 #[must_use = "this returns the trimmed string as a new slice, \
2939 without modifying the original"]
2940 #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
2941 #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
2942 #[inline]
2943 pub const fn trim_ascii_start(&self) -> &str {
2944 // SAFETY: Removing ASCII characters from a `&str` does not invalidate
2945 // UTF-8.
2946 unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii_start()) }
2947 }
2948
2949 /// Returns a string slice with trailing ASCII whitespace removed.
2950 ///
2951 /// 'Whitespace' refers to the definition used by
2952 /// [`u8::is_ascii_whitespace`].
2953 ///
2954 /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
2955 ///
2956 /// # Examples
2957 ///
2958 /// ```
2959 /// assert_eq!("\r hello world\u{3000}\n ".trim_ascii_end(), "\r hello world\u{3000}");
2960 /// assert_eq!(" ".trim_ascii_end(), "");
2961 /// assert_eq!("".trim_ascii_end(), "");
2962 /// ```
2963 #[must_use = "this returns the trimmed string as a new slice, \
2964 without modifying the original"]
2965 #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
2966 #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
2967 #[inline]
2968 pub const fn trim_ascii_end(&self) -> &str {
2969 // SAFETY: Removing ASCII characters from a `&str` does not invalidate
2970 // UTF-8.
2971 unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii_end()) }
2972 }
2973
2974 /// Returns a string slice with leading and trailing ASCII whitespace
2975 /// removed.
2976 ///
2977 /// 'Whitespace' refers to the definition used by
2978 /// [`u8::is_ascii_whitespace`].
2979 ///
2980 /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
2981 ///
2982 /// # Examples
2983 ///
2984 /// ```
2985 /// assert_eq!("\r hello world\n ".trim_ascii(), "hello world");
2986 /// assert_eq!(" ".trim_ascii(), "");
2987 /// assert_eq!("".trim_ascii(), "");
2988 /// ```
2989 #[must_use = "this returns the trimmed string as a new slice, \
2990 without modifying the original"]
2991 #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
2992 #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
2993 #[inline]
2994 pub const fn trim_ascii(&self) -> &str {
2995 // SAFETY: Removing ASCII characters from a `&str` does not invalidate
2996 // UTF-8.
2997 unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii()) }
2998 }
2999
3000 /// Returns an iterator that escapes each char in `self` with [`char::escape_debug`].
3001 ///
3002 /// Note: only extended grapheme codepoints that begin the string will be
3003 /// escaped.
3004 ///
3005 /// # Examples
3006 ///
3007 /// As an iterator:
3008 ///
3009 /// ```
3010 /// for c in "❤\n!".escape_debug() {
3011 /// print!("{c}");
3012 /// }
3013 /// println!();
3014 /// ```
3015 ///
3016 /// Using `println!` directly:
3017 ///
3018 /// ```
3019 /// println!("{}", "❤\n!".escape_debug());
3020 /// ```
3021 ///
3022 ///
3023 /// Both are equivalent to:
3024 ///
3025 /// ```
3026 /// println!("❤\\n!");
3027 /// ```
3028 ///
3029 /// Using `to_string`:
3030 ///
3031 /// ```
3032 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
3033 /// ```
3034 #[must_use = "this returns the escaped string as an iterator, \
3035 without modifying the original"]
3036 #[stable(feature = "str_escape", since = "1.34.0")]
3037 pub fn escape_debug(&self) -> EscapeDebug<'_> {
3038 let mut chars = self.chars();
3039 EscapeDebug {
3040 inner: chars
3041 .next()
3042 .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL))
3043 .into_iter()
3044 .flatten()
3045 .chain(chars.flat_map(CharEscapeDebugContinue)),
3046 }
3047 }
3048
3049 /// Returns an iterator that escapes each char in `self` with [`char::escape_default`].
3050 ///
3051 /// # Examples
3052 ///
3053 /// As an iterator:
3054 ///
3055 /// ```
3056 /// for c in "❤\n!".escape_default() {
3057 /// print!("{c}");
3058 /// }
3059 /// println!();
3060 /// ```
3061 ///
3062 /// Using `println!` directly:
3063 ///
3064 /// ```
3065 /// println!("{}", "❤\n!".escape_default());
3066 /// ```
3067 ///
3068 ///
3069 /// Both are equivalent to:
3070 ///
3071 /// ```
3072 /// println!("\\u{{2764}}\\n!");
3073 /// ```
3074 ///
3075 /// Using `to_string`:
3076 ///
3077 /// ```
3078 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
3079 /// ```
3080 #[must_use = "this returns the escaped string as an iterator, \
3081 without modifying the original"]
3082 #[stable(feature = "str_escape", since = "1.34.0")]
3083 pub fn escape_default(&self) -> EscapeDefault<'_> {
3084 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
3085 }
3086
3087 /// Returns an iterator that escapes each char in `self` with [`char::escape_unicode`].
3088 ///
3089 /// # Examples
3090 ///
3091 /// As an iterator:
3092 ///
3093 /// ```
3094 /// for c in "❤\n!".escape_unicode() {
3095 /// print!("{c}");
3096 /// }
3097 /// println!();
3098 /// ```
3099 ///
3100 /// Using `println!` directly:
3101 ///
3102 /// ```
3103 /// println!("{}", "❤\n!".escape_unicode());
3104 /// ```
3105 ///
3106 ///
3107 /// Both are equivalent to:
3108 ///
3109 /// ```
3110 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
3111 /// ```
3112 ///
3113 /// Using `to_string`:
3114 ///
3115 /// ```
3116 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
3117 /// ```
3118 #[must_use = "this returns the escaped string as an iterator, \
3119 without modifying the original"]
3120 #[stable(feature = "str_escape", since = "1.34.0")]
3121 pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
3122 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
3123 }
3124
3125 /// Returns the range that a substring points to.
3126 ///
3127 /// Returns `None` if `substr` does not point within `self`.
3128 ///
3129 /// Unlike [`str::find`], **this does not search through the string**.
3130 /// Instead, it uses pointer arithmetic to find where in the string
3131 /// `substr` is derived from.
3132 ///
3133 /// This is useful for extending [`str::split`] and similar methods.
3134 ///
3135 /// Note that this method may return false positives (typically either
3136 /// `Some(0..0)` or `Some(self.len()..self.len())`) if `substr` is a
3137 /// zero-length `str` that points at the beginning or end of another,
3138 /// independent, `str`.
3139 ///
3140 /// # Examples
3141 /// ```
3142 /// #![feature(substr_range)]
3143 ///
3144 /// let data = "a, b, b, a";
3145 /// let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap());
3146 ///
3147 /// assert_eq!(iter.next(), Some(0..1));
3148 /// assert_eq!(iter.next(), Some(3..4));
3149 /// assert_eq!(iter.next(), Some(6..7));
3150 /// assert_eq!(iter.next(), Some(9..10));
3151 /// ```
3152 #[must_use]
3153 #[unstable(feature = "substr_range", issue = "126769")]
3154 pub fn substr_range(&self, substr: &str) -> Option<Range<usize>> {
3155 self.as_bytes().subslice_range(substr.as_bytes())
3156 }
3157
3158 /// Returns the same string as a string slice `&str`.
3159 ///
3160 /// This method is redundant when used directly on `&str`, but
3161 /// it helps dereferencing other string-like types to string slices,
3162 /// for example references to `Box<str>` or `Arc<str>`.
3163 #[inline]
3164 #[unstable(feature = "str_as_str", issue = "130366")]
3165 #[ferrocene::prevalidated]
3166 pub const fn as_str(&self) -> &str {
3167 self
3168 }
3169}
3170
3171#[stable(feature = "rust1", since = "1.0.0")]
3172#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3173impl const AsRef<[u8]> for str {
3174 #[inline]
3175 #[ferrocene::prevalidated]
3176 fn as_ref(&self) -> &[u8] {
3177 self.as_bytes()
3178 }
3179}
3180
3181#[stable(feature = "rust1", since = "1.0.0")]
3182#[rustc_const_unstable(feature = "const_default", issue = "143894")]
3183impl const Default for &str {
3184 /// Creates an empty str
3185 #[inline]
3186 #[ferrocene::prevalidated]
3187 fn default() -> Self {
3188 ""
3189 }
3190}
3191
3192#[stable(feature = "default_mut_str", since = "1.28.0")]
3193#[rustc_const_unstable(feature = "const_default", issue = "143894")]
3194impl const Default for &mut str {
3195 /// Creates an empty mutable str
3196 #[inline]
3197 fn default() -> Self {
3198 // SAFETY: The empty string is valid UTF-8.
3199 unsafe { from_utf8_unchecked_mut(&mut []) }
3200 }
3201}
3202
3203impl_fn_for_zst! {
3204 /// A nameable, cloneable fn type
3205 #[derive(Clone)]
3206 struct LinesMap impl<'a> Fn = |line: &'a str| -> &'a str {
3207 let Some(line) = line.strip_suffix('\n') else { return line };
3208 let Some(line) = line.strip_suffix('\r') else { return line };
3209 line
3210 };
3211
3212 #[derive(Clone)]
3213 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
3214 c.escape_debug_ext(EscapeDebugExtArgs {
3215 escape_grapheme_extended: false,
3216 escape_single_quote: true,
3217 escape_double_quote: true
3218 })
3219 };
3220
3221 #[derive(Clone)]
3222 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
3223 c.escape_unicode()
3224 };
3225 #[derive(Clone)]
3226 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
3227 c.escape_default()
3228 };
3229
3230 #[derive(Clone)]
3231 struct IsWhitespace impl Fn = |c: char| -> bool {
3232 c.is_whitespace()
3233 };
3234
3235 #[derive(Clone)]
3236 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
3237 byte.is_ascii_whitespace()
3238 };
3239
3240 #[derive(Clone)]
3241 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
3242 !s.is_empty()
3243 };
3244
3245 #[derive(Clone)]
3246 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
3247 !s.is_empty()
3248 };
3249
3250 #[derive(Clone)]
3251 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
3252 // SAFETY: not safe
3253 unsafe { from_utf8_unchecked(bytes) }
3254 };
3255}
3256
3257// This is required to make `impl From<&str> for Box<dyn Error>` and `impl<E> From<E> for Box<dyn Error>` not overlap.
3258#[stable(feature = "error_in_core_neg_impl", since = "1.65.0")]
3259impl !crate::error::Error for &str {}