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