MST
星途 面试题库

面试题:Rust字符串查找替换在复杂场景下的应用

在一个Rust项目中,有一个字符串包含HTML标签和文本内容,格式类似`<p>Some text here <span>sub - text</span> more text</p>`。现在要求编写一个函数,将所有`<span>`标签内的文本替换为大写形式,而保持其他内容不变。请给出完整的Rust代码实现,同时考虑处理标签嵌套等复杂情况。
11.4万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
fn replace_span_text_to_uppercase(html: &str) -> String {
    let mut result = String::new();
    let mut inside_span = false;
    let mut tag_stack = Vec::new();
    let mut current_text = String::new();

    for c in html.chars() {
        if c == '<' {
            if!current_text.is_empty() {
                if inside_span {
                    result.push_str(&current_text.to_uppercase());
                } else {
                    result.push_str(&current_text);
                }
                current_text.clear();
            }
            let mut tag = String::new();
            for next_c in html[html.find('<').unwrap() + 1..].chars() {
                if next_c == '>' {
                    if tag.starts_with("span") && tag.ends_with("/") {
                        if let Some(_) = tag_stack.pop() {
                            inside_span = tag_stack.len() > 0 && tag_stack.last().unwrap() == "span";
                        }
                    } else if tag.starts_with("span") {
                        tag_stack.push("span".to_string());
                        inside_span = true;
                    } else if tag.starts_with("/span") {
                        if let Some(_) = tag_stack.pop() {
                            inside_span = tag_stack.len() > 0 && tag_stack.last().unwrap() == "span";
                        }
                    }
                    break;
                }
                tag.push(next_c);
            }
            result.push('<');
            result.push_str(&tag);
            result.push('>');
        } else {
            current_text.push(c);
        }
    }

    if!current_text.is_empty() {
        if inside_span {
            result.push_str(&current_text.to_uppercase());
        } else {
            result.push_str(&current_text);
        }
    }

    result
}

你可以使用以下方式测试这个函数:

fn main() {
    let html = "<p>Some text here <span>sub - text</span> more text</p>";
    let new_html = replace_span_text_to_uppercase(html);
    println!("{}", new_html);
}