public static class Spinner
{ private readonly static Random Randomizer = new Random(); public static string Spin(string content) { const char OPEN_BRACE = '{'; const char CLOSE_BRACE = '}'; const char DELIMITER = '|'; var start = content.IndexOf(OPEN_BRACE); var end = content.IndexOf(CLOSE_BRACE); if (start == -1 && end == -1 || start == -1 || end < start) { return content; } if (end == -1) { throw new ArgumentException("Unbalanced brace."); } var substring = content.Substring(start + 1, content.Length - (start + 1)); var rest = Spin(substring); end = rest.IndexOf(CLOSE_BRACE); if (end == -1) { throw new ArgumentException("Unbalanced brace."); } var splits = rest.Substring(0, end).Split(DELIMITER); var item = splits[Randomizer.Next(0, splits.Length)]; return content.Substring(0, start) + item + Spin(rest.Substring(end + 1, rest.Length - (end + 1))); } }
private void button11_Click(object sender, EventArgs e) { richTextBox4.Text = Spinner.Spin(richTextBox3.Text); }
private string returnSpinnedPart(string part) { Random random = new Random(); string[] values = part.Split('|'); if (values.Length > 0) return values[random.Next(0, values.Length)]; return ""; } private string returnSpinnedContent(string input) { string spinned = input; try { Regex regexObj = new Regex(@"\{.*?\}", RegexOptions.Singleline); MatchCollection m = regexObj.Matches(input); foreach (Match match in m) { string part = returnSpinnedPart(match.Value.Replace("{", "").Replace("}", "")); spinned = spinned.Replace(match.Value, part); } } catch (ArgumentException ex) { MessageBox.Show("RegEx prob"); } return spinned; } private void button12_Click(object sender, EventArgs e) { richTextBox4.Text = returnSpinnedContent(richTextBox3.Text); }
Hiç yorum yok:
Yorum Gönder