【问题标题】:How to trim space less than n times?如何修剪空间少于n次?
【发布时间】:2020-06-05 19:30:28
【问题描述】:

如何消除每行开头最多n个空格?

例如,当修剪 4 个空格时:

  • " 5" ->" 5"
  • " 4" ->"4"
  • " 3" ->"3"
const INPUT:&str = "    4\n  2\n0\n\n      6\n";
const OUTPUT:&str = "4\n2\n0\n\n  6\n";
#[test]
fn main(){
    assert_eq!(&trim_deindent(INPUT,4), OUTPUT)
}

【问题讨论】:

    标签: rust texttrimming


    【解决方案1】:

    我正要评论textwrap::dedent,但后来我注意到"2",它有不到4 个空格。所以你希望它继续删除空格,如果有的话,直到 4。

    只是写一个快速的解决方案,它可能看起来像这样:

    您的断言将通过,但请注意,以\r\n 结尾的行将转换为\n,因为lines 不提供区分\n 和\r\n 的方法。

    fn trim_deindent(text: &str, max: usize) -> String {
        let mut new_text = text
            .lines()
            .map(|line| {
                let mut max = max;
                line.chars()
                    // Skip while `c` is a whitespace and at most `max` spaces
                    .skip_while(|c| {
                        if max == 0 {
                            false
                        } else {
                            max -= 1;
                            c.is_whitespace()
                        }
                    })
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");
    
        // Did the original `text` end with a `\n` then add it again
        if text.ends_with('\n') {
            new_text.push('\n');
        }
    
        new_text
    }
    

    如果您想同时保留\n 和\r\n,则可以采用更复杂的方法扫描字符串,从而避免使用lines。

    fn trim_deindent(text: &str, max: usize) -> String {
        let mut new_text = String::new();
    
        let mut line_start = 0;
        loop {
            let mut max = max;
    
            // Skip `max` spaces
            let after_space = text[line_start..].chars().position(|c| {
                // We can't use `is_whitespace` here, as that will skip past `\n` and `\r` as well
                if (max == 0) || !is_horizontal_whitespace(c) {
                    true
                } else {
                    max -= 1;
                    false
                }
            });
    
            if let Some(after_space) = after_space {
                let after_space = line_start + after_space;
    
                let line = &text[after_space..];
                // Find `\n` or use the line length (if it's the last line)
                let end = line
                    .chars()
                    .position(|c| c == '\n')
                    .unwrap_or_else(|| line.len());
    
                // Push the line (including the line ending) onto `new_text`
                new_text.push_str(&line[..=end]);
    
                line_start = after_space + end + 1;
            } else {
                break;
            }
        }
    
        new_text
    }
    
    #[inline]
    fn is_horizontal_whitespace(c: char) -> bool {
        (c != '\r') && (c != '\n') && c.is_whitespace()
    }
    

    【讨论】:

    • @mcarton 您如何在不分配的情况下获取单个&amp;str 并返回多个单独的&amp;str?我可以看到返回 Vec&lt;&amp;str&gt; 的替代方案,但这将同样分配。
    • 没关系,我误读了 OP,虽然它只需要处理一行。
    • 可以直接收藏到String,而不是.collect::&lt;Vec&lt;_&gt;&gt;().join("\n")。
    • @Aloso 那么如何添加\n?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 2020-02-11
    • 1970-01-01
    • 2021-03-28
    • 2010-11-14
    • 2011-04-23
    • 1970-01-01
    相关资源
    最近更新 更多