Strings in Rust
Strings are a kind of little weird in rust. In the core language rust has only one kind of string i.e, “str”. Str is the immutable primitive string of fixed length.
The String type which is provided by Rust Standard Library (not coded in the core language) is mutable, growable, owned, UTF-8 encoded. Rust’s standard library also includes a number of other string types, such as
CStr. These string types can store text in different encodings or be represented in memory in a different way. Those are all advance concepts to grasp (consider reading documentation ).
Let’s concentrate on the two main types “str” and “String” types.
let _val= “hello”; // primitive string type immutable by default
let _val1= String::from(“Hello, World!”); // Growable and mutable
note:- We will apply all methods to String type, not str type.
- find the length using len() method which works for both types.
2. Add something to string push() and push_str() method.
Both methods have a different use case push() method can add only one character to the string while push_str() can add anything. Also, make sure you have defined a mutable type
here I have used push() method to add a Unicode character, let’s try to add a string using push();
Oh wao! compiler is yelling and that's the beauty of writing code in rust compiler acts as a mentor. The Rust compiler not only tells what is the error but explain it concisely.
So, to add a string to existing we will use push_str() method.
3. Capacity (no of bytes it can store) use capacity() method
4. is_empty() method to check if the string is empty or not and it returns a boolean (true or false);
5. contains() method can be used to find if some substring is present in the declared String. it also returns a boolean.
6. replace() use replace method to replace a substring with a different word.
We can also loop through a string like here we will loop through white space i.e, each word will be on a new line in the console.
We can also create String of certain capacity
let mut name = String::with_capcity(10);
You can use assertion in a string (for testing purposes)
look here we are getting an error as original length of st is 2 .
See this example:
It shows no error as our assertions are correct in both the cases.
For more strings methods go through below link.
We talked about strings in Chapter 4, but we'll look at them in more depth now. New Rustaceans commonly get stuck on…doc.rust-lang.org
To be continued……