[英]Replace given occurance of text in Ms Word document using C sharp
我正在使用c Sharp进行编码,我需要找到如何使用c Sharp替换给定出现的MS-Word文档中的文本。
我在网上发现了很多关于替换第一个事件并替换所有事件的示例,但在给定事件中没有一个。
我想要的示例如下:
你好世界你好测试测试你好..你好...测试你好
成为
你好世界你好测试测试你好..树...测试你好
那是“ hello”被“ tree”替换的第四次出现。
期待解决方案...
谢谢
试试这样的东西...
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 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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.