String Conversion
Part of the Fundamentals section of Coddy's Rust journey — lesson 71 of 75.
To convert a numeric type to a string, you can use the to_string() method. This method is available for most data types including integers and floating-point numbers.
For example:
let number = 42;
let number_str = number.to_string();
println!("The number as a string: {}", number_str);In this example, we're converting an i32 variable number to a String.
To convert a string to a numeric type, you can use the parse() method. This method returns a result that contains either the parsed number or an error if the conversion fails.
For example:
let number_str = "123";
let number: i32 = number_str.parse().unwrap();
println!("The number as an i32: {}", number);In this example, we're converting a string number_str to an i32 using the parse() method. The unwrap() method is used to extract the value from the Result, assuming that the conversion is successful.
If the conversion fails, the program will panic (fail).
You can also use parse() with different numeric types:
let float_str = "3.14";
let float_num: f64 = float_str.parse().unwrap();
println!("The number as an f64: {}", float_num);In this case, we're converting a string float_str to an f64.
Challenge
EasyCreate a function named convert_and_print that takes three arguments:
- A string slice
s: &str— this is a number written as text (e.g."123.67"). It is only used whento_stringisfalse. - A float
n: f64— a floating-point number. It is only used whento_stringistrue. - A boolean
to_string: bool— determines which operation to perform.
The function should perform the following operations:
- If
to_stringistrue: convertnto a string using.to_string(), then count how many digit characters it contains (do not count the dot.or the minus sign-). Print in the format:Number: [string], Digits: [num of digits]
For example, ifn = -321.198623, its string form is"-321.198623", which has 9 digit characters (not counting-and.).
Hint: convertnto a string, then use.len()on it and subtract 1 for each.or-it contains. - If
to_stringisfalse: parse the stringsas anf64using.parse(), then cast it toi32(which drops the decimal part). Print in the format:String as number: [number]
For example, ifs = "123.67231", the output isString as number: 123.
Call convert_and_print twice:
- First, with
to_stringset tofalse— this uses the stringsand ignoresn. - Second, with
to_stringset totrue— this uses the numbernand ignoress.
Cheat sheet
To convert a numeric type to a string, use the to_string() method:
let number = 42;
let number_str = number.to_string();To convert a string to a numeric type, use the parse() method:
let number_str = "123";
let number: i32 = number_str.parse().unwrap();The parse() method works with different numeric types:
let float_str = "3.14";
let float_num: f64 = float_str.parse().unwrap();The unwrap() method extracts the value from the Result. If the conversion fails, the program will panic.
Try it yourself
use std::io;
fn convert_and_print(s: &str, n: f64, to_string: bool) {
// Write your code here
}
fn main() {
let mut input_number_str = String::new();
let mut input_n = String::new();
io::stdin().read_line(&mut input_number_str).unwrap();
io::stdin().read_line(&mut input_n).unwrap();
let n: f64 = input_n.trim().parse().unwrap();
let number_str = input_number_str.trim();
// Call convert_and_print with to_string = false
// Call convert_and_print with to_string = true
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input