Implements the + operator for concatenating two strings.
This consumes the String on the left-hand side and re-uses its buffer (growing it if\nnecessary). This is done to avoid allocating a new String and copying the entire contents on\nevery operation, which would lead to O(n^2) running time when building an n-byte string by\nrepeated concatenation.
The string on the right-hand side is only borrowed; its contents are copied into the returned\nString.
Concatenating two Strings takes the first by value and borrows the second:
let a = String::from(\"hello\");\nlet b = String::from(\" world\");\nlet c = a + &b;\n// `a` is moved and can no longer be used here.If you want to keep using the first String, you can clone it and append to the clone instead:
let a = String::from(\"hello\");\nlet b = String::from(\" world\");\nlet c = a.clone() + &b;\n// `a` is still valid here.Concatenating &str slices can be done by converting the first to a String:
let a = \"hello\";\nlet b = \" world\";\nlet c = a.to_string() + b;Implements the += operator for appending to a String.
This has the same behavior as the push_str method.
+= operation. Read moreextend_one)extend_one)extend_one)extend_one)extend_one)extend_one)extend_one)extend_one)extend_one)extend_one)extend_one)extend_one)extend_one)extend_one)extend_one)extend_one)Converts a clone-on-write string to an owned\ninstance of String.
This extracts the owned string,\nclones the string if it is not already owned.
\n// If the string is not owned...\nlet cow: Cow<'_, str> = Cow::Borrowed(\"eggplant\");\n// It will allocate on the heap and copy the string.\nlet owned: String = String::from(cow);\nassert_eq!(&owned[..], \"eggplant\");dst to replace the current match. Read moreCreates a new empty String.
Given that the String is empty, this will not allocate any initial\nbuffer. While that means that this initial operation is very\ninexpensive, it may cause excessive allocation later when you add\ndata. If you have an idea of how much data the String will hold,\nconsider the with_capacity method to prevent excessive\nre-allocation.
let s = String::new();Creates a new empty String with at least the specified capacity.
Strings have an internal buffer to hold their data. The capacity is\nthe length of that buffer, and can be queried with the capacity\nmethod. This method creates an empty String, but one with an initial\nbuffer that can hold at least capacity bytes. This is useful when you\nmay be appending a bunch of data to the String, reducing the number of\nreallocations it needs to do.
If the given capacity is 0, no allocation will occur, and this method\nis identical to the new method.
let mut s = String::with_capacity(10);\n\n// The String contains no chars, even though it has capacity for more\nassert_eq!(s.len(), 0);\n\n// These are all done without reallocating...\nlet cap = s.capacity();\nfor _ in 0..10 {\n s.push('a');\n}\n\nassert_eq!(s.capacity(), cap);\n\n// ...but this may make the string reallocate\ns.push('a');try_with_capacity)Converts a vector of bytes to a String.
A string (String) is made of bytes (u8), and a vector of bytes\n(Vec<u8>) is made of bytes, so this function converts between the\ntwo. Not all byte slices are valid Strings, however: String\nrequires that it is valid UTF-8. from_utf8() checks to ensure that\nthe bytes are valid UTF-8, and then does the conversion.
If you are sure that the byte slice is valid UTF-8, and you don’t want\nto incur the overhead of the validity check, there is an unsafe version\nof this function, from_utf8_unchecked, which has the same behavior\nbut skips the check.
This method will take care to not copy the vector, for efficiency’s\nsake.
\nIf you need a &str instead of a String, consider\nstr::from_utf8.
The inverse of this method is into_bytes.
Returns Err if the slice is not UTF-8 with a description as to why the\nprovided bytes are not UTF-8. The vector you moved in is also included.
Basic usage:
\n\n// some bytes, in a vector\nlet sparkle_heart = vec![240, 159, 146, 150];\n\n// We know these bytes are valid, so we'll use `unwrap()`.\nlet sparkle_heart = String::from_utf8(sparkle_heart).unwrap();\n\nassert_eq!(\"💖\", sparkle_heart);Incorrect bytes:
\n\n// some invalid bytes, in a vector\nlet sparkle_heart = vec![0, 159, 146, 150];\n\nassert!(String::from_utf8(sparkle_heart).is_err());See the docs for FromUtf8Error for more details on what you can do\nwith this error.
Converts a slice of bytes to a string, including invalid characters.
\nStrings are made of bytes (u8), and a slice of bytes\n(&[u8]) is made of bytes, so this function converts\nbetween the two. Not all byte slices are valid strings, however: strings\nare required to be valid UTF-8. During this conversion,\nfrom_utf8_lossy() will replace any invalid UTF-8 sequences with\nU+FFFD REPLACEMENT CHARACTER, which looks like this: �
If you are sure that the byte slice is valid UTF-8, and you don’t want\nto incur the overhead of the conversion, there is an unsafe version\nof this function, from_utf8_unchecked, which has the same behavior\nbut skips the checks.
This function returns a Cow<'a, str>. If our byte slice is invalid\nUTF-8, then we need to insert the replacement characters, which will\nchange the size of the string, and hence, require a String. But if\nit’s already valid UTF-8, we don’t need a new allocation. This return\ntype allows us to handle both cases.
Basic usage:
\n\n// some bytes, in a vector\nlet sparkle_heart = vec![240, 159, 146, 150];\n\nlet sparkle_heart = String::from_utf8_lossy(&sparkle_heart);\n\nassert_eq!(\"💖\", sparkle_heart);Incorrect bytes:
\n\n// some invalid bytes\nlet input = b\"Hello \\xF0\\x90\\x80World\";\nlet output = String::from_utf8_lossy(input);\n\nassert_eq!(\"Hello �World\", output);string_from_utf8_lossy_owned)Converts a Vec<u8> to a String, substituting invalid UTF-8\nsequences with replacement characters.
See from_utf8_lossy for more details.
Note that this function does not guarantee reuse of the original Vec\nallocation.
Basic usage:
\n\n#![feature(string_from_utf8_lossy_owned)]\n// some bytes, in a vector\nlet sparkle_heart = vec![240, 159, 146, 150];\n\nlet sparkle_heart = String::from_utf8_lossy_owned(sparkle_heart);\n\nassert_eq!(String::from(\"💖\"), sparkle_heart);Incorrect bytes:
\n\n#![feature(string_from_utf8_lossy_owned)]\n// some invalid bytes\nlet input: Vec<u8> = b\"Hello \\xF0\\x90\\x80World\".into();\nlet output = String::from_utf8_lossy_owned(input);\n\nassert_eq!(String::from(\"Hello �World\"), output);Decode a native endian UTF-16–encoded vector v into a String,\nreturning Err if v contains any invalid data.
// 𝄞music\nlet v = &[0xD834, 0xDD1E, 0x006d, 0x0075,\n 0x0073, 0x0069, 0x0063];\nassert_eq!(String::from(\"𝄞music\"),\n String::from_utf16(v).unwrap());\n\n// 𝄞mu<invalid>ic\nlet v = &[0xD834, 0xDD1E, 0x006d, 0x0075,\n 0xD800, 0x0069, 0x0063];\nassert!(String::from_utf16(v).is_err());Decode a native endian UTF-16–encoded slice v into a String,\nreplacing invalid data with the replacement character (U+FFFD).
Unlike from_utf8_lossy which returns a Cow<'a, str>,\nfrom_utf16_lossy returns a String since the UTF-16 to UTF-8\nconversion requires a memory allocation.
// 𝄞mus<invalid>ic<invalid>\nlet v = &[0xD834, 0xDD1E, 0x006d, 0x0075,\n 0x0073, 0xDD1E, 0x0069, 0x0063,\n 0xD834];\n\nassert_eq!(String::from(\"𝄞mus\\u{FFFD}ic\\u{FFFD}\"),\n String::from_utf16_lossy(v));str_from_utf16_endian)Decode a UTF-16LE–encoded vector v into a String,\nreturning Err if v contains any invalid data.
Basic usage:
\n\n#![feature(str_from_utf16_endian)]\n// 𝄞music\nlet v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,\n 0x73, 0x00, 0x69, 0x00, 0x63, 0x00];\nassert_eq!(String::from(\"𝄞music\"),\n String::from_utf16le(v).unwrap());\n\n// 𝄞mu<invalid>ic\nlet v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,\n 0x00, 0xD8, 0x69, 0x00, 0x63, 0x00];\nassert!(String::from_utf16le(v).is_err());str_from_utf16_endian)Decode a UTF-16LE–encoded slice v into a String, replacing\ninvalid data with the replacement character (U+FFFD).
Unlike from_utf8_lossy which returns a Cow<'a, str>,\nfrom_utf16le_lossy returns a String since the UTF-16 to UTF-8\nconversion requires a memory allocation.
Basic usage:
\n\n#![feature(str_from_utf16_endian)]\n// 𝄞mus<invalid>ic<invalid>\nlet v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,\n 0x73, 0x00, 0x1E, 0xDD, 0x69, 0x00, 0x63, 0x00,\n 0x34, 0xD8];\n\nassert_eq!(String::from(\"𝄞mus\\u{FFFD}ic\\u{FFFD}\"),\n String::from_utf16le_lossy(v));str_from_utf16_endian)Decode a UTF-16BE–encoded vector v into a String,\nreturning Err if v contains any invalid data.
Basic usage:
\n\n#![feature(str_from_utf16_endian)]\n// 𝄞music\nlet v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,\n 0x00, 0x73, 0x00, 0x69, 0x00, 0x63];\nassert_eq!(String::from(\"𝄞music\"),\n String::from_utf16be(v).unwrap());\n\n// 𝄞mu<invalid>ic\nlet v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,\n 0xD8, 0x00, 0x00, 0x69, 0x00, 0x63];\nassert!(String::from_utf16be(v).is_err());str_from_utf16_endian)Decode a UTF-16BE–encoded slice v into a String, replacing\ninvalid data with the replacement character (U+FFFD).
Unlike from_utf8_lossy which returns a Cow<'a, str>,\nfrom_utf16le_lossy returns a String since the UTF-16 to UTF-8\nconversion requires a memory allocation.
Basic usage:
\n\n#![feature(str_from_utf16_endian)]\n// 𝄞mus<invalid>ic<invalid>\nlet v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,\n 0x00, 0x73, 0xDD, 0x1E, 0x00, 0x69, 0x00, 0x63,\n 0xD8, 0x34];\n\nassert_eq!(String::from(\"𝄞mus\\u{FFFD}ic\\u{FFFD}\"),\n String::from_utf16be_lossy(v));vec_into_raw_parts)Decomposes a String into its raw components: (pointer, length, capacity).
Returns the raw pointer to the underlying data, the length of\nthe string (in bytes), and the allocated capacity of the data\n(in bytes). These are the same arguments in the same order as\nthe arguments to from_raw_parts.
After calling this function, the caller is responsible for the\nmemory previously managed by the String. The only way to do\nthis is to convert the raw pointer, length, and capacity back\ninto a String with the from_raw_parts function, allowing\nthe destructor to perform the cleanup.
#![feature(vec_into_raw_parts)]\nlet s = String::from(\"hello\");\n\nlet (ptr, len, cap) = s.into_raw_parts();\n\nlet rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };\nassert_eq!(rebuilt, \"hello\");Creates a new String from a pointer, a length and a capacity.
This is highly unsafe, due to the number of invariants that aren’t\nchecked:
\nVec::<u8>::from_raw_parts.String::from_utf8_unchecked.Violating these may cause problems like corrupting the allocator’s\ninternal data structures. For example, it is normally not safe to\nbuild a String from a pointer to a C char array containing UTF-8\nunless you are certain that array was originally allocated by the\nRust standard library’s allocator.
The ownership of buf is effectively transferred to the\nString which may then deallocate, reallocate or change the\ncontents of memory pointed to by the pointer at will. Ensure\nthat nothing else uses the pointer after calling this\nfunction.
use std::mem;\n\nunsafe {\n let s = String::from(\"hello\");\n\n // Prevent automatically dropping the String's data\n let mut s = mem::ManuallyDrop::new(s);\n\n let ptr = s.as_mut_ptr();\n let len = s.len();\n let capacity = s.capacity();\n\n let s = String::from_raw_parts(ptr, len, capacity);\n\n assert_eq!(String::from(\"hello\"), s);\n}Converts a vector of bytes to a String without checking that the\nstring contains valid UTF-8.
See the safe version, from_utf8, for more details.
This function is unsafe because it does not check that the bytes passed\nto it are valid UTF-8. If this constraint is violated, it may cause\nmemory unsafety issues with future users of the String, as the rest of\nthe standard library assumes that Strings are valid UTF-8.
// some bytes, in a vector\nlet sparkle_heart = vec![240, 159, 146, 150];\n\nlet sparkle_heart = unsafe {\n String::from_utf8_unchecked(sparkle_heart)\n};\n\nassert_eq!(\"💖\", sparkle_heart);Converts a String into a byte vector.
This consumes the String, so we do not need to copy its contents.
let s = String::from(\"hello\");\nlet bytes = s.into_bytes();\n\nassert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);Extracts a string slice containing the entire String.
let s = String::from(\"foo\");\n\nassert_eq!(\"foo\", s.as_str());Converts a String into a mutable string slice.
let mut s = String::from(\"foobar\");\nlet s_mut_str = s.as_mut_str();\n\ns_mut_str.make_ascii_uppercase();\n\nassert_eq!(\"FOOBAR\", s_mut_str);Appends a given string slice onto the end of this String.
let mut s = String::from(\"foo\");\n\ns.push_str(\"bar\");\n\nassert_eq!(\"foobar\", s);Copies elements from src range to the end of the string.
Panics if the starting point or end point do not lie on a char\nboundary, or if they’re out of bounds.
let mut string = String::from(\"abcde\");\n\nstring.extend_from_within(2..);\nassert_eq!(string, \"abcdecde\");\n\nstring.extend_from_within(..2);\nassert_eq!(string, \"abcdecdeab\");\n\nstring.extend_from_within(4..8);\nassert_eq!(string, \"abcdecdeabecde\");Returns this String’s capacity, in bytes.
let s = String::with_capacity(10);\n\nassert!(s.capacity() >= 10);Reserves capacity for at least additional bytes more than the\ncurrent length. The allocator may reserve more space to speculatively\navoid frequent allocations. After calling reserve,\ncapacity will be greater than or equal to self.len() + additional.\nDoes nothing if capacity is already sufficient.
Panics if the new capacity overflows usize.
Basic usage:
\n\nlet mut s = String::new();\n\ns.reserve(10);\n\nassert!(s.capacity() >= 10);This might not actually increase the capacity:
\n\nlet mut s = String::with_capacity(10);\ns.push('a');\ns.push('b');\n\n// s now has a length of 2 and a capacity of at least 10\nlet capacity = s.capacity();\nassert_eq!(2, s.len());\nassert!(capacity >= 10);\n\n// Since we already have at least an extra 8 capacity, calling this...\ns.reserve(8);\n\n// ... doesn't actually increase.\nassert_eq!(capacity, s.capacity());Reserves the minimum capacity for at least additional bytes more than\nthe current length. Unlike reserve, this will not\ndeliberately over-allocate to speculatively avoid frequent allocations.\nAfter calling reserve_exact, capacity will be greater than or equal to\nself.len() + additional. Does nothing if the capacity is already\nsufficient.
Panics if the new capacity overflows usize.
Basic usage:
\n\nlet mut s = String::new();\n\ns.reserve_exact(10);\n\nassert!(s.capacity() >= 10);This might not actually increase the capacity:
\n\nlet mut s = String::with_capacity(10);\ns.push('a');\ns.push('b');\n\n// s now has a length of 2 and a capacity of at least 10\nlet capacity = s.capacity();\nassert_eq!(2, s.len());\nassert!(capacity >= 10);\n\n// Since we already have at least an extra 8 capacity, calling this...\ns.reserve_exact(8);\n\n// ... doesn't actually increase.\nassert_eq!(capacity, s.capacity());Tries to reserve capacity for at least additional bytes more than the\ncurrent length. The allocator may reserve more space to speculatively\navoid frequent allocations. After calling try_reserve, capacity will be\ngreater than or equal to self.len() + additional if it returns\nOk(()). Does nothing if capacity is already sufficient. This method\npreserves the contents even if an error occurs.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::TryReserveError;\n\nfn process_data(data: &str) -> Result<String, TryReserveError> {\n let mut output = String::new();\n\n // Pre-reserve the memory, exiting if we can't\n output.try_reserve(data.len())?;\n\n // Now we know this can't OOM in the middle of our complex work\n output.push_str(data);\n\n Ok(output)\n}Tries to reserve the minimum capacity for at least additional bytes\nmore than the current length. Unlike try_reserve, this will not\ndeliberately over-allocate to speculatively avoid frequent allocations.\nAfter calling try_reserve_exact, capacity will be greater than or\nequal to self.len() + additional if it returns Ok(()).\nDoes nothing if the capacity is already sufficient.
Note that the allocator may give the collection more space than it\nrequests. Therefore, capacity can not be relied upon to be precisely\nminimal. Prefer try_reserve if future insertions are expected.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::TryReserveError;\n\nfn process_data(data: &str) -> Result<String, TryReserveError> {\n let mut output = String::new();\n\n // Pre-reserve the memory, exiting if we can't\n output.try_reserve_exact(data.len())?;\n\n // Now we know this can't OOM in the middle of our complex work\n output.push_str(data);\n\n Ok(output)\n}Shrinks the capacity of this String to match its length.
let mut s = String::from(\"foo\");\n\ns.reserve(100);\nassert!(s.capacity() >= 100);\n\ns.shrink_to_fit();\nassert_eq!(3, s.capacity());Shrinks the capacity of this String with a lower bound.
The capacity will remain at least as large as both the length\nand the supplied value.
\nIf the current capacity is less than the lower limit, this is a no-op.
\nlet mut s = String::from(\"foo\");\n\ns.reserve(100);\nassert!(s.capacity() >= 100);\n\ns.shrink_to(10);\nassert!(s.capacity() >= 10);\ns.shrink_to(0);\nassert!(s.capacity() >= 3);Shortens this String to the specified length.
If new_len is greater than or equal to the string’s current length, this has no\neffect.
Note that this method has no effect on the allocated capacity\nof the string
\nPanics if new_len does not lie on a char boundary.
let mut s = String::from(\"hello\");\n\ns.truncate(2);\n\nassert_eq!(\"he\", s);Removes a char from this String at byte position idx and returns it.
Copies all bytes after the removed char to new positions.
\nNote that calling this in a loop can result in quadratic behavior.
\nPanics if idx is larger than or equal to the String’s length,\nor if it does not lie on a char boundary.
let mut s = String::from(\"abç\");\n\nassert_eq!(s.remove(0), 'a');\nassert_eq!(s.remove(1), 'ç');\nassert_eq!(s.remove(0), 'b');string_remove_matches)Remove all matches of pattern pat in the String.
#![feature(string_remove_matches)]\nlet mut s = String::from(\"Trees are not green, the sky is not blue.\");\ns.remove_matches(\"not \");\nassert_eq!(\"Trees are green, the sky is blue.\", s);Matches will be detected and removed iteratively, so in cases where\npatterns overlap, only the first pattern will be removed:
\n\n#![feature(string_remove_matches)]\nlet mut s = String::from(\"banana\");\ns.remove_matches(\"ana\");\nassert_eq!(\"bna\", s);Retains only the characters specified by the predicate.
\nIn other words, remove all characters c such that f(c) returns false.\nThis method operates in place, visiting each character exactly once in the\noriginal order, and preserves the order of the retained characters.
let mut s = String::from(\"f_o_ob_ar\");\n\ns.retain(|c| c != '_');\n\nassert_eq!(s, \"foobar\");Because the elements are visited exactly once in the original order,\nexternal state may be used to decide which elements to keep.
\n\nlet mut s = String::from(\"abcde\");\nlet keep = [false, true, true, false, true];\nlet mut iter = keep.iter();\ns.retain(|_| *iter.next().unwrap());\nassert_eq!(s, \"bce\");Inserts a character into this String at byte position idx.
Reallocates if self.capacity() is insufficient, which may involve copying all\nself.capacity() bytes. Makes space for the insertion by copying all bytes of\n&self[idx..] to new positions.
Note that calling this in a loop can result in quadratic behavior.
\nPanics if idx is larger than the String’s length, or if it does not\nlie on a char boundary.
let mut s = String::with_capacity(3);\n\ns.insert(0, 'f');\ns.insert(1, 'o');\ns.insert(2, 'o');\n\nassert_eq!(\"foo\", s);Inserts a string slice into this String at byte position idx.
Reallocates if self.capacity() is insufficient, which may involve copying all\nself.capacity() bytes. Makes space for the insertion by copying all bytes of\n&self[idx..] to new positions.
Note that calling this in a loop can result in quadratic behavior.
\nPanics if idx is larger than the String’s length, or if it does not\nlie on a char boundary.
let mut s = String::from(\"bar\");\n\ns.insert_str(0, \"foo\");\n\nassert_eq!(\"foobar\", s);Returns a mutable reference to the contents of this String.
This function is unsafe because the returned &mut Vec allows writing\nbytes which are not valid UTF-8. If this constraint is violated, using\nthe original String after dropping the &mut Vec may violate memory\nsafety, as the rest of the standard library assumes that Strings are\nvalid UTF-8.
let mut s = String::from(\"hello\");\n\nunsafe {\n let vec = s.as_mut_vec();\n assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);\n\n vec.reverse();\n}\nassert_eq!(s, \"olleh\");Returns the length of this String, in bytes, not chars or\ngraphemes. In other words, it might not be what a human considers the\nlength of the string.
let a = String::from(\"foo\");\nassert_eq!(a.len(), 3);\n\nlet fancy_f = String::from(\"ƒoo\");\nassert_eq!(fancy_f.len(), 4);\nassert_eq!(fancy_f.chars().count(), 3);Returns true if this String has a length of zero, and false otherwise.
let mut v = String::new();\nassert!(v.is_empty());\n\nv.push('a');\nassert!(!v.is_empty());Splits the string into two at the given byte index.
\nReturns a newly allocated String. self contains bytes [0, at), and\nthe returned String contains bytes [at, len). at must be on the\nboundary of a UTF-8 code point.
Note that the capacity of self does not change.
Panics if at is not on a UTF-8 code point boundary, or if it is beyond the last\ncode point of the string.
let mut hello = String::from(\"Hello, World!\");\nlet world = hello.split_off(7);\nassert_eq!(hello, \"Hello, \");\nassert_eq!(world, \"World!\");Truncates this String, removing all contents.
While this means the String will have a length of zero, it does not\ntouch its capacity.
let mut s = String::from(\"foo\");\n\ns.clear();\n\nassert!(s.is_empty());\nassert_eq!(0, s.len());\nassert_eq!(3, s.capacity());Removes the specified range from the string in bulk, returning all\nremoved characters as an iterator.
\nThe returned iterator keeps a mutable borrow on the string to optimize\nits implementation.
\nPanics if the starting point or end point do not lie on a char\nboundary, or if they’re out of bounds.
If the returned iterator goes out of scope without being dropped (due to\ncore::mem::forget, for example), the string may still contain a copy\nof any drained characters, or may have lost characters arbitrarily,\nincluding characters outside the range.
let mut s = String::from(\"α is alpha, β is beta\");\nlet beta_offset = s.find('β').unwrap_or(s.len());\n\n// Remove the range up until the β from the string\nlet t: String = s.drain(..beta_offset).collect();\nassert_eq!(t, \"α is alpha, \");\nassert_eq!(s, \"β is beta\");\n\n// A full range clears the string, like `clear()` does\ns.drain(..);\nassert_eq!(s, \"\");string_into_chars)Converts a String into an iterator over the chars of the string.
As a string consists of valid UTF-8, we can iterate through a string\nby char. This method returns such an iterator.
It’s important to remember that char represents a Unicode Scalar\nValue, and might not match your idea of what a ‘character’ is. Iteration\nover grapheme clusters may be what you actually want. That functionality\nis not provided by Rust’s standard library, check crates.io instead.
Basic usage:
\n\n#![feature(string_into_chars)]\n\nlet word = String::from(\"goodbye\");\n\nlet mut chars = word.into_chars();\n\nassert_eq!(Some('g'), chars.next());\nassert_eq!(Some('o'), chars.next());\nassert_eq!(Some('o'), chars.next());\nassert_eq!(Some('d'), chars.next());\nassert_eq!(Some('b'), chars.next());\nassert_eq!(Some('y'), chars.next());\nassert_eq!(Some('e'), chars.next());\n\nassert_eq!(None, chars.next());Remember, chars might not match your intuition about characters:
#![feature(string_into_chars)]\n\nlet y = String::from(\"y̆\");\n\nlet mut chars = y.into_chars();\n\nassert_eq!(Some('y'), chars.next()); // not 'y̆'\nassert_eq!(Some('\\u{0306}'), chars.next());\n\nassert_eq!(None, chars.next());Removes the specified range in the string,\nand replaces it with the given string.\nThe given string doesn’t need to be the same length as the range.
\nPanics if the starting point or end point do not lie on a char\nboundary, or if they’re out of bounds.
let mut s = String::from(\"α is alpha, β is beta\");\nlet beta_offset = s.find('β').unwrap_or(s.len());\n\n// Replace the range up until the β from the string\ns.replace_range(..beta_offset, \"Α is capital alpha; \");\nassert_eq!(s, \"Α is capital alpha; β is beta\");Converts this String into a Box<str>.
Before doing the conversion, this method discards excess capacity like shrink_to_fit.\nNote that this call may reallocate and copy the bytes of the string.
let s = String::from(\"hello\");\n\nlet b = s.into_boxed_str();Consumes and leaks the String, returning a mutable reference to the contents,\n&'a mut str.
The caller has free choice over the returned lifetime, including 'static. Indeed,\nthis function is ideally used for data that lives for the remainder of the program’s life,\nas dropping the returned reference will cause a memory leak.
It does not reallocate or shrink the String, so the leaked allocation may include unused\ncapacity that is not part of the returned slice. If you want to discard excess capacity,\ncall into_boxed_str, and then Box::leak instead. However, keep in mind that\ntrimming the capacity may result in a reallocation and copy.
let x = String::from(\"bucket\");\nlet static_ref: &'static mut str = x.leak();\nassert_eq!(static_ref, \"bucket\");SocketAddrs. Read moreConverts a CString into a String if it contains valid UTF-8 data.
This method is equivalent to CString::into_string.