2011-05-13 2 views
1

예리한 C로 코딩하고 나는 예리한 방법을 사용하여 MS-Word 문서에서 주어진 텍스트를 대체하는 방법을 찾아야합니다.C를 사용하여 Ms Word 문서의 주어진 출현을 바꾸십시오. 날카로운

첫 번째 발생을 대체하고 모든 발생을 대체하는 것과 관련하여 웹상에서 많은 사례를 발견했습니다.

다음과 같이 I이 원하는 것을 예 :

안녕하세요 세계 안녕하세요 테스트 테스트 안녕하세요 .. 안녕하세요 ... 테스트 인사를

안녕하세요

할 수 세계 안녕 테스트 시험 안녕하세요 .. 트리 ... 시험 안녕

'tree'로 대체되는 'hello'의 네 번째 어커런스입니다.

감사

이 작동
+0

Word 문서 (예 : 매크로)에서 실행되는 코드를 작성 하시겠습니까? 아니면 Word 문서를 수정하는 서버에서 코드를 실행 하시겠습니까? –

+0

실제로 나는 http://www.codeproject.com/KB/edit/Application_to_Word.aspx에서 그 길을 원합니다. 이 링크는 하나를 대체하고 모두 바꾸는 방법을 제공합니다. 그래서 나는 그런 식으로하고 싶습니다. 내가 필요로하는 것은 –

답변

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);'여기서 input은 될 문자열입니다. 수색했다. –

관련 문제