面试题答案
一键面试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(¤t_text.to_uppercase());
} else {
result.push_str(¤t_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(¤t_text.to_uppercase());
} else {
result.push_str(¤t_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);
}