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