MOCKSTACKS
EN
Questions And Answers

More Tutorials








RUST String Methods - String Object

Below table show the common string methods supported by RUST

Method Signature Description
new() pub const fn new() -> String Creates a new empty String.
to_string() fn to_string(&self) -> String  Converts the given value to a String.
replace()  pub fn replace<'a, P>(&'a self, from: P, to: &str) -> String Replaces all matches of a pattern with another string. 
as_str()  pub fn as_str(&self) -> &str Extracts a string slice containing the entire string. 
push() pub fn push(&mut self, ch: char)  Appends the given char to the end of this String.
push_str()  pub fn push_str(&mut self, string: &str)  Appends a given string slice onto the end of this String.
len() pub fn len(&self) -> usize  Returns the length of this String, in bytes.
trim() pub fn trim(&self) -> &str Returns a string slice with leading and trailing whitespace removed.
split_whitespa ce()  pub fn split_whitespace(&self) - > SplitWhitespace Splits a string slice by whitespace and returns an iterator.
split() pub fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> , where P is pattern can be &str, char, or a closure that determines the split. Returns an iterator over substrings of this string slice, separated by characters matched by a pattern.
chars() pub fn chars(&self) -> Chars Returns an iterator over the chars of a string slice.


new() Example

An empty string object is created using the new() method and its value is set to hello.

fn main(){
 let mut name = String::new();
 name.push_str("Jhon");
 println!("{}",name);
}

Output

Jhon



to_string() Example

To access all methods of String object, convert a string literal to object type using the to_string() function.

fn main(){
 let full_Name = "Jhon Smith".to_string();
 println!("{}",full_Name );
}

Output

Jhon Smith


replace() Example

The replace() function takes two parameters – the first parameter is a string pattern to search for and the second parameter is the new value to be replaced.

fn main(){
 let hellowWorld = "Hello World";
 let helloPeter= hellowWorld .replace("World","Peter");
 println!("{}",helloPeter);
}

Output

Hello Peter


as_str() Example

The as_str() function extracts a string slice containing the entire string.

fn main(){
 let first_Name= String::from("Jhon");
 let first_Name_As_String= first_Name.as_str();
 println!("First Name As String {}",first_Name_As_String);

}

Output

First Name As String Jhon



push() Example

The push() function appends the given char to the end of this String.

fn main(){
 let books= String::from("My book");
 books.push('s');
 println!("{}",books);

}

Output

My books


push_str() Example

The push_str() function appends a given string slice onto the end of a String.

fn main(){
 let book= String::from("My book");
 book.push_str(' is completed.');
 println!("{}",book);

}

Output

My book is completed.


len() Example

The len() function returns the total number of characters in a string (including spaces).

fn main(){
 let fullname = "Jhon Smith";
 println!("length is {}",fullname.len());
}

Output

length is 10


trim() Example

The trim() function removes leading and trailing spaces in a string. NOTE that this function will not remove the inline spaces.

fn main(){
 let fullname = "       Jhon Smith   ";
 println!("length is {}",fullname.trim().len());
}

Output

length is 10


split_whitespace() Example

The split_whitespace() splits the input string into different strings.

fn main(){
 let msg = "Car Bus Bike Boat".to_string();
 for token in msg.split_whitespace(){
 println!("Word: {}",token);
}

Output

Word: Car
Word: Bus
Word: Bike
Word: Boat


split() Example

The split() string method returns an iterator over substrings of a string slice, separated by characters matched by a pattern. The limitation of the split() method is that the result cannot be stored for later use. The collect method can be used to store the result returned by split() as a vector.

Example might be hard to understand now, it's better to understand RUST Array First.

fn main(){
 let fullname = "Jhon,William,Charles";

 for token in fullname.split(","){
  println!("Name is {}",token);
 }
}

Output

Name is Jhon
Name is William
Name is Charles


chars() Example

Individual characters in a string can be accessed using the chars method.

fn main(){
 let word = "Mock".to_string();
 for char_in_word in word.chars(){
  println!("{}",char_in_word);
 }
}

Output

M
o
c
k


Conclusion

In this page (written and validated by ) you learned about Rust String Methods - String Object . What's Next? If you are interested in completing Rust tutorial, your next topic will be learning about: Rust String Concatenation.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.