Rust不使用正则表达式如何删除字符串中的无用空格?


Rust中替换字符串的空格:将两个空格减为一个,并移除\n、\r\n、制表符前后的空格:

fn magic(input: &str) -> String {
    input

        // 修剪前面和后面的空格
        .trim()
       
// 分割成行
        .lines()
        .map(|part| {
           
// 对于每一行
            part
               
// 修剪前导和尾部的空白处
                .trim()
               
//对空白处进行分割。
               
//包括字符串被分割的空白处
               
// 分割后的部分
                .split_inclusive(char::is_whitespace)
               
// 过滤掉只包含空白的子字符串
                .filter(|part| !part.trim().is_empty())
               
//为这一行收集成一个字符串
                .collect()
        })
       
//收集成一个字符串的Vec
        .collect::<Vec<String>>()
       
//用换行符连接这些字符串
       
//返回到最终的字符串中
        .join(
"\n")
}

playground


或者:

fn magic(input: &str) -> String {
    let mut output: String = input
        // trim leading and trailing space
        .trim()
       
// split into lines
        .lines()
        .flat_map(|part| {
           
// for each line
            part
               
// trim leading and trailing space
                .trim()
               
// split on whitespace
               
// including the space where the string was split
                .split_inclusive(char::is_whitespace)
               
// filter out substrings containing only whitespace
                .filter(|part| !part.trim().is_empty())
               
// add a newline after each line
                .chain([
"\n"])
        })
       
// collect into a String
        .collect();
    
   
// remove the last newline
    output.truncate(output.len() - 1);
    
    output
}

#[test]
fn test() {
   
// assert_eq!(&magic("  "), " ");
    
    assert_eq!(
        &magic(
"     a l    l   lower      "),
       
"a l l lower"
    );
    
    assert_eq!(
        &magic(
"     i need\nnew  lines \n\nmany   times     "),
       
"i need\nnew lines\n\nmany times"
    );
    
    assert_eq!(&magic(
"  à   la  "), "à la");
}

playground