查看该解决方案,以便从输入字符串中提取、替换和删除数据。
以下代码是上一单元中所述挑战的一种可能的解决方案。
const string input = "<div><h2>Widgets ™</h2><span>5000</span></div>";
string quantity = "";
string output = "";
// Your work here
// Extract the "quantity"
const string openSpan = "<span>";
const string closeSpan = "</span>";
int quantityStart = input.IndexOf(openSpan) + openSpan.Length; // + length of <span> so index at end of <span> tag
int quantityEnd= input.IndexOf(closeSpan);
int quantityLength = quantityEnd - quantityStart;
quantity = input.Substring(quantityStart, quantityLength);
quantity = $"Quantity: {quantity}";
// Set output to input, replacing the trademark symbol with the registered trademark symbol
const string tradeSymbol = "™";
const string regSymbol = "®";
output = input.Replace(tradeSymbol, regSymbol);
// Remove the opening <div> tag
const string openDiv = "<div>";
int divStart = output.IndexOf(openDiv);
output = output.Remove(divStart, openDiv.Length);
// Remove the closing </div> tag and add "Output:" to the beginning
const string closeDiv = "</div>";
int divCloseStart = output.IndexOf(closeDiv);
output = "Output: " + output.Remove(divCloseStart, closeDiv.Length);
Console.WriteLine(quantity);
Console.WriteLine(output);
此代码只是“一种可能的解决方案”。只要代码生成以下输出,就成功了。
Quantity: 5000
Output: <h2>Widgets ®</h2><span>5000</span>
如果成功,恭喜! 继续进行下一个单元中的知识检查。
重要
如果在完成此项挑战时遇到问题,可能需要先回顾前面的几个单元,然后再继续。