Link Search Menu Expand Document

Solution : Concatenate Words Starting With ‘c’

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 rustlabs. Read it with full concentration to grasp the content of the labs";

    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 type String 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, an if condition checks if the starting letter of the word (splitted on space) is c using the starts_with() method, then - appends the word in my_updated_string on line 5. - appends the space in my_updated_string on line 6.
  • 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.