Why does my string not match when reading user input from stdin?

Instead of trim_end_matches (previously called trim_right_matches), I’d recommend using trim_end (previously called trim_right) or even better, just trim: use std::io; fn main() { let mut correct_name = String::new(); io::stdin() .read_line(&mut correct_name) .expect(“Failed to read line”); let correct_name = correct_name.trim(); if correct_name == “y” { println!(“matched y!”); } else if correct_name == “n” { println!(“matched n!”); … Read more

Convert integers to strings to create output filenames at run time

you can write to a unit, but you can also write to a string program foo character(len=1024) :: filename write (filename, “(A5,I2)”) “hello”, 10 print *, trim(filename) end program Please note (this is the second trick I was talking about) that you can also build a format string programmatically. program foo character(len=1024) :: filename character(len=1024) … Read more

How to compare strings in Bash

Using variables in if statements if [ “$x” = “valid” ]; then echo “x has the value ‘valid'” fi If you want to do something when they don’t match, replace = with !=. You can read more about string operations and arithmetic operations in their respective documentation. Why do we use quotes around $x? You … Read more

Escape a string for a sed replace pattern

Warning: This does not consider newlines. For a more in-depth answer, see this SO-question instead. (Thanks, Ed Morton & Niklas Peter) Note that escaping everything is a bad idea. Sed needs many characters to be escaped to get their special meaning. For example, if you escape a digit in the replacement string, it will turn … Read more

Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?

TL;DR: One can instead use &str, &[T] or &T to allow for more generic code. One of the main reasons to use a String or a Vec is because they allow increasing or decreasing the capacity. However, when you accept an immutable reference, you cannot use any of those interesting methods on the Vec or … Read more