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