2010-12-06 64 views
1

我發現這裏與我的問題有點相關:在文本字符串中隨機插入網址標記c#

Inject HTML markup around certain words in a string

但我想隨機插入鏈接的地方。我的應用程序是Windows窗體應用程序。在一個框中我給文字,在另一個框中給我的網址。在第三個框中,我希望輸出帶有隨機包含某些詞語的URL。

一個例子可以是,給出上面的文本輸出應該是這樣的。

但我想在隨機地方插入<"a href="http://foo.com">links<"/a>

+2

你編寫一個應用程序生成的垃圾郵件?你爲什麼要在*「隨機地方」插入超鏈接*或「隨機附帶一些詞」? – 2010-12-06 04:57:25

+0

請使用一些標點符號讓人們更容易閱讀您的信息。聽起來像一個相當to application的應用程序給我。 – 2010-12-06 05:01:40

回答

1

下面是一些psudo代碼:

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

如果你已經嘗試對自己的東西,請張貼在這裏,我們可以使用它作爲一個基地。

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; 

    }