我在这里找到了与我的问题有些相关的内容:
Inject HTML markup around certain words in a string
但我想在随机位置插入链接。我的应用程序是Windows窗体应用程序。在一个框中我给出了文本,在另一个框中我给出了URL。在第三个框中,我希望输出带有URL,我随机地将这些URL包裹起来。
一个例子可以是,上面给出的文字输出应该是。
但我想在随机位置插入<"a href="http://foo.com">links<"/a>
。
答案 0 :(得分:1)
这是一些伪代码:
//Find the length of the given string you want to insert into
//Foreach link calculate a random number between 0 and String.Length
//Insert that link into that position.
如果您已经尝试过自己的东西,请在此处发布,我们可以将其作为基础。
答案 1 :(得分:0)
ArrayList usedPositions = new ArrayList();
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
txtOriginal.Text="this string is to test. a quick brown fox jump over the lazy dog. dog bytes on fox's leg ang gosht";
}
private void btnConvert_Click(object sender, EventArgs e)
{
string stringToModify = getString();
string[] words=splitWords(stringToModify);
string urls = txtUrls.Text;
string[] urlString = urls.Split(',');
for(int i=0;i<urlString.Length;i++)
{
string url = urlString[i];
Random index = new Random();
int position = index.Next(words.Length);
if (checkIfUsed(position) == false)
{
usedPositions.Add(position);
string tempWord = words[position];
tempWord = "<a href='" + url + "'>" + tempWord + "</a>";
words[position] = tempWord;
}
else
i--;
}
/*if(txtUrls!=null)
{
for (int i = 0; i < urlString.Length; i++)
{
stringToModify.Replace(words[position], "<a href=" + urlString[i] + ">" + words[position] + "</a>");
}
}
* */
}
//function to check if random place already used
private bool checkIfUsed(int radomNum)
{
if (usedPositions.Contains(radomNum))
return true;
else
return false;
}
private string getString()
{
string myString = txtOriginal.Text;
string mySubString = myString.Substring(0, 2 * (myString.Length / 3));
return mySubString;
}
//so i can get word to wrap html around it
private string[] splitWords(string s)
{
string[] words= Regex.Split(s, @"/W+");
return words;
}