For example I have text like this - "i want to buy a {car|home|etc}". Is there any lib to randomize text? I.e. make 3 strings
i want to 开发者_如何学Gobuy a car i want to buy a home i want to buy a etc
You could predefine the strings in an array that then generate a random integer using the Random class.
var string[] data = new string[] {"car", "home", "etc"};
var rand = new Random();
var text = "I want to buy a " + data[rand.Next(data.Length)];
I think this is a job for Regex.Replace:
private void button1_Click(object sender, EventArgs e)
{
string text = Regex.Replace(textBox1.Text, "{(.*?)}", PickRandomWord);
...
}
private Random random = new Random();
private string PickRandomWord(Match match)
{
string[] words = match.Groups[1].Value.Split('|');
return words[random.Next(words.Length)];
}
This will pick one random text.
First I think you have to create your own words dictionary
After use some randomizer, for example this one: Random Sentences and Paragraphs
EDIT
There are could be plenty of other type of solutions, so please clarify your problem to get more correct answer.
Regards.
public String CalculateRandomString(String input)
{
String s = input.Substring(0, input.IndexOf('{'));
String choiceString = input.Substring(input.IndexOf('{'), input.IndexOf('}'));
String[] choices = choiceString.Split('|');
Random rand = new Random();
int choice = rand.Next(0, choices.Length);
return s + choices[choice];
}
Notes:
- Only works if the choices are at the end of the string.
//demonstration
index = string.indexOf('{');
if(index != -1)
{
string.remove(0, index);
endIndex = string.indexOf('}', index);
if(endIndex != -1)
{
list = string.remove(endIndex, string.length - endIndex).split('|').toList();
return list[rand.next(list.count)];
}
}
If you want it to parse every instance, then set it in a while loop that checks if the index is -1 and use string.insert();
This is the function I made for spinable text
private string spinString(string s)
{
string ret,
temp;
string[] spinables;
int index,
i;
Random a;
a = new Random();
ret = null;
i = 0;
while (true)
{
if (i == s.Length)
break;
if (s[i] == '{')
{
temp = s.Remove(0, i + 1);
index = temp.IndexOf('}');
if (index != -1)
{
temp = temp.Remove(index, temp.Length - index);
spinables = temp.Split('|');
temp = spinables[a.Next(spinables.Count())];
index = s.IndexOf('}', i);
if (index != -1)
{
s = s.Remove(i, index - i + 1);
s = s.Insert(i, temp);
}
}
}
try
{
ret += s[i];
}
catch (Exception e)
{
e.ToString();
break;
}
i++;
Thread.Sleep(10);
}
return ret;
}
Try this -
String[] strings = {"car", "home", "boat"};
var output = "I want to buy a " + strings.OrderBy(en => System.Guid.NewGuid()).First();
精彩评论