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