To check if a string starts with a specific prefix in Rust, you can use the starts_with()
method of the String class.
In this example,
str1
with a value of "Hello World"
.starts_with()
method of the string object str1
with the prefix "Hello"
.starts_with()
method returns true
if the string starts with the specified prefix; otherwise, it returns false
.fn main() {
let str1 = String::from("Hello World");
let starts_with_hello = str1.starts_with("Hello");
println!("String starts with prefix 'Hello': {}", starts_with_hello);
}
String starts with prefix 'Hello': true
In this example,
str2
with a value of "apple"
.starts_with()
method of the string object str2
with the prefix "banana"
.starts_with()
method returns true
if the string starts with the specified prefix; otherwise, it returns false
.fn main() {
let str2 = String::from("apple");
let starts_with_banana = str2.starts_with("banana");
println!("String starts with prefix 'banana': {}", starts_with_banana);
}
String starts with prefix 'banana': false
In this tutorial, we learned How to Check if String starts with Specific Prefix in Rust language with well detailed examples.