Rust Lang

String Matching in Rust

In Rust, a string refers to a collection of Unicode scalar values which are encoded as a sequence of bytes. In Rust, we use the string type to represent the string data type. The string type is a mutable, heap-allocated data structure.

At a lower level, a string in Rust is a contiguous block of memory which is allocated on the heap using the “malloc” function. The size of the buffer is mainly determined by the capacity of the input string that is specified by the byte size of the buffer.

As you can guess, the string type in Rust provides a high-level interface to create and work with string values in a Rust application. This includes the methods for creating, modifying, and manipulating the strings.

One of the major string manipulation and operation methods is string matching. This post teaches us how to perform the string matching in Rust using various techniques.

String Matching in Rust

String matching refers to finding one or more occurrences of a pattern within a more extensive set of strings or characters. String matching is a prevalent task in programming and is often found in tools such as grep, awk, and other text processing tools. It is also helpful in search engines, data mining, and more.

In Rust, we can use the match control flow to create a program that performs a pattern matching on a given set of strings.

The match construct takes an expression to match against and a set of options, each containing the pattern and the code to execute if the match is found.

We can express the syntax of the match string as shown in the following:

match expression {
    pattern1 => {
        // code to execute if the expression matches pattern1
    }
    pattern2 => {
    }
        // if none matches
    }
}

 

Consider the following example that demonstrates the use of the match construct to find a matching string:

fn main() {
    let my_str = String::from("hi");

    match my_str.as_str() {
        "hi" => print!("Hi, back!"),
        "hello" => print!("Hello back"),
        _ => print!("No Match Found")
    }
}

 

In the previous example, we start by creating a new variable called “my_str” of string type and initialize it with the “hi” value using the String::from method.

We then use a match statement to compare the value of “my_str” to various string literals. Finally, we use the as_str method

If “my_str” matches the “hi” string literal, the program prints “Hi, back!” to the console using the print! macro.

If “my_str” matches the literal “hello” string, the program prints “Hello back” to the console.

Finally, if “my_str” does not match any previous string literals, the program prints “No Match Found”.

Once we run the previous code, it should print “Hi, back!”

Contains() Method in Rust String Matching

We can also use Rust’s contains() method to check if a given string matches a specific pattern.

The contains() method checks if a given string slice or character set is in a larger string. If true, the method returns a Boolean true. Otherwise, it returns false.

The function syntax is as follows:

fn contains(&self, pat: &str) -> bool

 

The contains() method takes one argument, “pat”, which denotes the pattern to search for in the string. This can be a single character or a string slice.

Consider the following example:

fn main() {
let my_str = "hello world";
if my_str.contains("hello") {
    println!("The string contains 'hello'");
}
if my_str.contains('w') {
    println!("The string contains 'w'");
}
}

 

In the previous example, we use the contains() method to check if the “hello world” string contains either the hello substring or the “w” character.

The resulting output is as follows:

The string contains 'hello'
The string contains 'w'

 

It is good to remember that the contains() method is case-sensitive. Therefore, to perform a case-insensitive search, you can convert the input string and pattern to lowercase or uppercase before invoking the contains() method.

Conclusion

We discussed how to use the match construct in Rust and the contains() method to match a specific string pattern to a larger text.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list