Strip Prefix And Suffix From Strings
strip_prefix and strip_suffix return Option of the remaining borrowed slice, so unmatched input becomes None instead of a silently wrong string.
Code
fn normalize_module(arg: &str) -> &str {
// strings 的 strip_prefix 返回 Option<&str>:剥离后借用剩余部分,不分配
match arg.strip_prefix("./") {
Some(rest) => rest,
None => arg,
}
}
fn main() {
let args = ["./src/lib.rs", "src/main.rs", "./", "pages/about.md"];
for arg in args {
println!("{arg} -> {}", normalize_module(arg));
}
// strip_suffix 配合 if let 处理扩展名
let file = "report-2026.json";
if let Some(stem) = file.strip_suffix(".json") {
println!("stem: {stem}");
}
// 没有匹配时得到 None,而不是被误改的字符串
let wrong = "data.csv";
println!("csv stripped: {:?}", wrong.strip_suffix(".json"));
}How the snippet works
Strip Prefix And Suffix From Strings keeps everything in the functions normalize_module and main.
Repetition is confined to for arg in args — the rest of the file is straight-line. The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.
Applying it
The primary signature is fn normalize_module(arg: &str) -> &str
The demo output is labeled (stem:, csv stripped:); each label names the call that printed it.
Execute the file and main walks through normalize_module, in that order.
Statements that matter
if let Some(stem) = file.strip_suffix(".json") {
println!("stem: {stem}");
}
fn normalize_module(arg: &str) -> &str {
// strings 的 strip_prefix 返回 Option<&str>:剥离后借用剩余部分,不分配
match arg.strip_prefix("./") {
Some(rest) => rest,
None => arg,
}
}
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Strip Prefix And Suffix From Strings print when run?
- Invoke the file as-is — the `stem:`, `csv stripped:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.