檢閱從輸入字串擷取、取代和移除資料的解決方案
下列程式碼是先前單元中挑戰的其中一個可能解決方案。
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>
如果成功,恭喜您! 請繼續進行下一個單元中的知識檢定。
重要
如果您無法順利完成此挑戰,您應該在繼續之前先複習上一個單元中的內容。