Skip to content

文本解析

字符串分割

分割符分割

rust
let text = "a,b,c,d";
let parts: Vec<&str> = text.split(',').collect();	// 单个分割符

let text = "a->b->c";
let parts: Vec<&str> = text.split("->").collect();	// 多字符作为分割符

按空格分割

rust
let text = "a b  c\td";
let parts: Vec<&str> = text.split_whitespace().collect();

按行分割

rust
let text = "line1\nline2\nline3";
let lines: Vec<&str> = text.lines().collect();

字符串提取(和切片)

范围截取

rust
let text = "hello world";
let hello = &text[0..5];
let world = &text[6..11];

去除空格

rust
let text = "  hello  ";
let trimmed = text.trim();        // "hello" 去除首尾空格
let trim_start = text.trim_start(); // "hello  " 去除头部空格
let trim_end = text.trim_end();   // "  hello" 去除尾部空格

替换

替换所有

rust
let text = "hello world";
let replaced = text.replace("world", "Rust"); // "hello Rust"

let multiple = "a a a".replace("a", "b"); // "b b b"

替换前n项

rust
let text = "a a a a";
let replaced = text.replacen("a", "b", 2); // "b b a a"

正则表达式