Convert string to int in Rust

Rust-Programs

In this example, we are going to learn about How to Convert string to int in Rust. We will learn this with multiple solutions. So let us begin with our program.

1. Program to convert string to int in Rust


In our first approach we are going to make use of trim(), parse(), and unwrap() functions of strings. This approach works for both String and &str strings in Rust.

Rust Program to convert string to int

fn main() {

    let char = "43";
    let num : i32 = char.trim().parse().unwrap();
    println!("The converted number is :");
    println!("{}", num + 1);

}

Output

 rustc -o main main.rs
 ./main
The converted number is :
44

2. Program to convert string to int in Rust


In this approach, we are going to use another approach. This approach makes use of the from_str() function of the FromStr() trait. Let us first understand this in detail before we jump to the code examples.

Syntax

pub trait FromStr {
    type Err;
    fn from_str(s: &str) -> Result<Self, Self::Err>;
}

from_str() : methods Parse a value from a string.FromStr’s from_str method is often used implicitly, through str’s parse method. This we saw in the example above.

FromStr does not have a lifetime parameter, and so you can only parse types that do not contain a lifetime parameter themselves. In other words, you can parse an i32 with FromStr, but not a &i32.You can parse a struct that contains an i32, but not one that contains an &i32.

Rust Program to convert string to int

use std::str::FromStr;

fn main() {

		let s = "15";
		let x = i32::from_str(s).unwrap();

		assert_eq!(15, x);
		println!("The converted number is :");
		println!("{}", x + 1);

}

Output

 rustc -o main main.rs
 ./main
The converted number is :
16
 ^C
