How to remove file extension in Rust

3 Answers

0 votes
use std::path::Path;

/// Removes the last file extension from a filename or path.
///
/// Examples:
/// - "document.pdf"      -> "document"
/// - "archive.tar.gz"    -> "archive.tar"
/// - "photo.jpg"         -> "photo"
/// - "README"            -> "README"
/// - "/tmp/file.txt"     -> "/tmp/file"
///
/// # Arguments
///
/// * `path` - A filename or full path.
///
/// # Returns
///
/// A new `String` containing the path without its last extension.
fn remove_file_extension(path: &str) -> String {
    let file_path = Path::new(path);

    match file_path.file_stem() {
        Some(stem) => {
            if let Some(parent) = file_path.parent() {
                if parent.as_os_str().is_empty() {
                    stem.to_string_lossy().into_owned()
                } else {
                    parent
                        .join(stem)
                        .to_string_lossy()
                        .into_owned()
                }
            } else {
                stem.to_string_lossy().into_owned()
            }
        }
        None => path.to_string(),
    }
}

fn main() {
    println!("{}", remove_file_extension("document.pdf"));
    println!("{}", remove_file_extension("archive.tar.gz"));
    println!("{}", remove_file_extension("/tmp/file.txt"));
    println!("{}", remove_file_extension("README"));
}



/*
run:

document
archive.tar
/tmp/file
README

*/

 



answered Oct 12 by avibootz
0 votes
use std::path::Path;

/// Removes the last file extension from a filename or path.
fn remove_file_extension(path: &str) -> String {
    let path = Path::new(path);

    match (path.parent(), path.file_stem()) {
        (_, None) => path.to_string_lossy().into_owned(),
        (Some(parent), Some(stem)) if !parent.as_os_str().is_empty() => {
            parent.join(stem).to_string_lossy().into_owned()
        }
        (_, Some(stem)) => stem.to_string_lossy().into_owned(),
    }
}

fn main() {
    println!("{}", remove_file_extension("document.pdf"));
    println!("{}", remove_file_extension("archive.tar.gz"));
    println!("{}", remove_file_extension("/tmp/file.txt"));
    println!("{}", remove_file_extension("README"));
}


/*
run:

document
archive.tar
/tmp/file
README

*/

 



answered Oct 12 by avibootz
0 votes
/// Removes the last extension using string operations.
fn remove_file_extension(path: &str) -> String {
    match path.rfind('.') {
        Some(pos) => path[..pos].to_string(),
        None => path.to_string(),
    }
}

fn main() {
    println!("{}", remove_file_extension("document.pdf"));
    println!("{}", remove_file_extension("archive.tar.gz"));
    println!("{}", remove_file_extension("/tmp/file.txt"));
    println!("{}", remove_file_extension("README"));
}


/*
run:

document
archive.tar
/tmp/file
README

*/

 



answered Oct 12 by avibootz
...