【问题标题】:Replace given occurance of text in Ms Word document using C sharp使用升 C 替换 Ms Word 文档中给定的文本
【发布时间】:2011-08-24 19:16:33
【问题描述】:

我正在用 c 语言进行编码,我需要找到如何替换 a 中给定的文本出现 使用升c的MS-Word文档。

我在网上找到了很多关于替换第一个匹配项和替换所有匹配项但在给定匹配项上没有替换的示例。

我想要的一个例子如下:

你好世界你好测试测试你好 ..你好......测试你好

成为

你好世界你好测试测试你好 .. 树 ... 测试你好

这是第 4 次出现 'hello' 被 'tree' 替换。

期待解决方案...

谢谢

【问题讨论】:

  • 您的意思是您要编写在 Word 文档中执行的代码(如宏),还是要在修改 Word 文档的服务器上执行代码?
  • 其实我想在codeproject.com/KB/edit/Application_to_Word.aspx中挡道。此链接提供如何替换一个和替换所有。所以我想要那样,这就是我所需要的

标签: c# text ms-word replace


【解决方案1】:

这行得通。希望这是您正在寻找的:

        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";
            }
        }

【讨论】:

    【解决方案2】:

    试试这样的...

    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;

    【讨论】:

    • 你可以这样使用...string output = ReplaceOccurrence(input, "hello","test",4); 其中输入是要搜索的字符串。
    猜你喜欢
    • 2011-08-28
    • 2020-08-27
    • 2013-08-21
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    相关资源
    最近更新 更多