もとねた: ずんだのMARQUEE問題
この程度の問題だと、正規表現や文字列置換などを利用して、解くことを考えるのが一般的だと思います。"もとねた"でもそのような解き方を採用していますが、せっかくなので別の切り口を考えてみたい。そこで、以下では<h1>test</h1>
というような文字列をxmlの1要素とみなし、C#に標準で用意されているXML読み込み用のライブラリを利用して、解答を試みています。
using System;
using System.Linq;
using System.Xml.Linq;
namespace Zunda
{
class Program
{
static void Main(string[] args)
{
var xml = @"
<h1>test</h1>
<h2>test</h2>
<h3>test</h3>
<div>div test1</div>
<div>div test2</div>
<div>div test3</div>
";
var elements = xml.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(line =>
{
var element = XElement.Parse(line);
var name = element.Name.LocalName;
return name.StartsWith("h") ? new XElement("marquee", element.Value, new XAttribute("scrollamount", name.Substring(1))) : element;
});
foreach (var element in elements)
{
Console.WriteLine(element);
}
}
}
}
以上の実行結果は次の通りになるはずです。
<marquee scrollamount="1">test</marquee>
<marquee scrollamount="2">test</marquee>
<marquee scrollamount="3">test</marquee>
<div>div test1</div>
<div>div test2</div>
<div>div test3</div>