开发者

insert urls markup in text string randomly c#

I found a somewhat related to my question here:

Inject HTML markup around certain words in a string.

But I want to insert links at random places. My application is a Windows Form application. In one box I give text, in another I give URLs. In 开发者_如何学运维a third box I want output with URLs which I give wrapped around some words randomly.

An example can be, given above text output should be like.

But I want to insert <"a href="http://foo.com">links<"/a> at random places.


Here is some psudo code:

//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.

If you have tried something on your own please post it here and we can use that as a base.


well it kind of very messy but here it is:

    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;

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜