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