Solution Review: Concatenate Words Starting With 'c'
This lesson gives a detailed solution review of the challenge in the previous lesson.
We'll cover the following
Solution:
fn test(my_str:String)-> String {let mut my_updated_string = "".to_string();for word in my_str.split(" "){if word.starts_with("c"){my_updated_string.push_str(word);my_updated_string.push(' ');}}my_updated_string.pop();my_updated_string}fn main(){let my_str= "This is a comprehensive course in Rust programming language on Educative. Read it with full concentration to grasp the content of the course";println!("Original String: {}", my_str);let updated_string = test(my_str.to_string());println!("Updated String: {}", updated_string);}
Explanation
-
On line 1, a String object
my_str
is passed as an argument. -
On line 2,
my_updated_string
of typeString
is initialized with the value null. -
On line 3, the string is traversed using a
for
loop that splits on whitespace using the.split
method.- On line 4 to line 7, within the
for
loop, anif
condition checks if the starting letter of the word (splitted on space) isc
using thestarts_with()
method, then- appends the word in
my_updated_string
on line 5. - appends the space in
my_updated_string
on line 6.
- appends the word in
- On line 4 to line 7, within the
-
On line 9, the appended space at the end is removed by using the
pop
function. -
After the loop terminates the variable
my_updated_string()
is returned.
The following illustration explains the above concept:
The string is shortened just to give you an idea of how this code executes.
Now that you have learned about Strings, let’s learn about a growable array called “Vectors” in the next chapter.
Create a free account to access the full course.
Learn to code, grow your skills, and succeed in your tech interview
By signing up, you agree to Educative's Terms of Service and Privacy Policy