2011-05-13 82 views
1

我使用c sharp編碼,並且需要找到如何使用c sharp替換 MS-Word文檔中給定出現的文本。使用C sharp替換Ms Word文檔中給定的文本的發生

我在網上發現了很多關於替換第一次出現的例子,並且替換了所有出現的事件,但是在給定事件中沒有。

什麼,我要的是如下的例子:

的hello world你好試驗測試你好 ..你好......你好測試

打招呼世界你好測試測試你好 ..樹...測試你好

這是第4次'hello'被'tree'取代。

期待一個解決方案...

感謝

+0

你的意思是你想要編寫在Word文檔(如宏)中執行的代碼,或者你想要在修改Word文檔的服務器上執行代碼嗎? – 2011-05-13 10:08:00

+0

其實我想在http://www.codeproject.com/KB/edit/Application_to_Word.aspx的方式。此鏈接提供瞭如何替換一個並全部替換。所以我想這樣,這就是我需要的 – 2011-05-13 10:36:21

回答

0

這工作。希望這是你在找什麼:

 string s = "hello world hello test testing hello .. hello ... test hello"; 
     string[] value = { "hello" }; 
     string[] strList = s.Split(value,255,StringSplitOptions.None); 
     string newStr = ""; 
     int replacePos = 4; 
     for (int i = 0; i < strList.Length; i++) 
     { 
      if ((i != replacePos - 1) && (strList.Length != i + 1)) 
      { 
       newStr += strList[i] + value[0]; 
      } 
      else if (strList.Length != i + 1) 
      { 
       newStr += strList[i] + "tree"; 
      } 
     } 
1

嘗試這樣的事情......

static string ReplaceOccurrence(string input, string wordToReplace, string replaceWith, int occToReplace) 
     { 
      MatchCollection matches = Regex.Matches(input, string.Format("([\\w]*)", wordToReplace), RegexOptions.IgnoreCase); 
      int occurrencesFound = 0; 
      int captureIndex = 0; 

      foreach (Match matchItem in matches) 
      { 
       if (matchItem.Value == wordToReplace) 
       { 
        occurrencesFound++; 
        if (occurrencesFound == occToReplace) 
        { 
         captureIndex = matchItem.Index; 
         break; 
        } 
       } 
      } 
      if (captureIndex > 0) 
      { 
       return string.Format("{0}{1}{2}", input.Substring(0, captureIndex), replaceWith, input.Substring(captureIndex + wordToReplace.Length)); 
      } else 
      { 
       return input; 
      } 
     } 

你將不得不把using System.Text.RegularExpressions;在頂部。

+0

你可以像這樣使用這個... 'string output = ReplaceOccurrence(input,「hello」,「test」,4);'where input is the string to be string搜索。 – 2011-05-13 10:14:59

相關問題