How it works...

In this recipe, we assign a variable named rand_string with a string value of I love Rust cookbook in which we perform a certain set of string operations.

In the first print statement, we display the length of the string by the len() method of the str type by calling rand_string.len() and correspondingly in the next print statement we use the split_at() method which expects an input argument which splits the string at the value of the argument passed and in our case we call rand_string.split_at(7) to split at index 7 of the string and assign it to the two variables named first and second, here space occupies an index value.

In the third print statement, we print the numbers of characters present by using the chars() and count() methods, we do it with the following syntax rand_string.chars().count() where chars() iterates through the characters and count() for counting the number of elements.

The loop is an iterative statement that keeps on running until the break key is called. We used the match function, which is similar to switch in other languages. We created different conditions for it to check and perform certain actions.

In the match statements, we have two conditions which are Some(x) and None. In both the cases, we perform unique operations which are as follows:

  • In the case of Some(x), it basically says that x is a value that exists and has a type T so we can use the x variable for further operations and in such cases, we print the value
  • In the case of None, it refers to cases where a value does not exist which ideally is the end of the string and the operation we perform at these cases are to break the loop

We iterate over three types of conditions:

  • The first set is individual cases, where we print all the characters of the string and is performed by the chars() and next() functions with the preceding match statements
  • The second set is where we print all the different words of the string by splitting in the places of white spaces and is performed by the split_whitespace() and next() functions with the preceding match statements
  • The last ones where we print all the different lines of the string by splitting in the places of next line and is performed by the lines() and next() functions with the preceding match statements
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.235.144