|
using System; using System.Collections.Generic; using System.Windows.Forms;
namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { string[] lines = { "うしかもしか", "ヌー", "かもしか", "ウシ科", "かも", "鳥類", "もしかしたら", "仮定", "りんご", "果物", }; string pattern = "かもしか"; // 偶数番の文字列と"かもしか"をマッチさせる。 // マッチしたら次行(奇数番)をプリントする。 for (int i = 0; i < lines.Length; i += 2) { if (match(lines[i], pattern)) { MessageBox.Show(lines[i + 1]); } }
}
// 候補となる部分文字列を長いものから列挙する public static IEnumerable<string> SubStrings(string source, int min_len) { for (int len = source.Length; len >= min_len; --len) { for (int pos = 0; pos <= source.Length - len; ++pos) { yield return source.Substring(pos, len); } } }
// patternから列挙される部分文字列を targetが含むなら true を返す public static bool match(string target, string pattern) { foreach (string sub in SubStrings(pattern, 3)) { if (target.IndexOf(sub) >= 0) return true; } return false; }
} }
フォーム、ボタンは環境に合わせてください。 ※説明どおりにコピペで動きましたよ。
|