2011-05-13 81 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

相关问题