Replace String in Word with New String in C#, VB.NET

Word Replace function enables users to replace specified strings with new ones. All numbers of string will be detected and replaced at once time. Spire.Doc for .NET provides document.Replace method to realize replace function in C#, VB.NET. The following screenshot is the result after replacing.

Replace Word Text

By invoking document.Replace method, users can replace particular string with new value and set if the replacement is case-sensitive or the whole word will be affected. There are five possibilities document.Replace method provides.

  • Replace all entries of matchString(which will be replaced) regular expression with new value string.
  • Replace all entries of matchString regular expression with text range holder.
  • Replace specified matchString in matchDoc (specified document), taking into consideration of case-sensitive and whole word options.
  • Replace all entries of mathString with new value string, taking into consideration of case-sensitive and whole word options.
  • Replace all entries of matchString with text selection, taking into consideration of case-sensitive and whole word options.

This guide will introduce how to realize the fourth possibility above to replace the string "New Zealand" in the loaded document with "NZ". Download and install Spire.Doc for .NET. Follow the code:

using Spire.Doc;

namespace ReplaceString
    class Program
        static void Main(string[] args)
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\New Zealand.docx");

            document.Replace("New Zealand", "NZ", false, true);

            document.SaveToFile("Replace.docx", FileFormat.Docx);
Imports Spire.Doc

Namespace ReplaceString
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\WordDocuments\New Zealand.docx")

            document.Replace("New Zealand", "NZ", False, True)

            document.SaveToFile("Replace.docx", FileFormat.Docx)
        End Sub
    End Class
End Namespace

Spire.Doc, a professional Word component, enables developers/programmers perform a wide range of processing tasks, such as generate, write, modify and save for their customize .NET, Silverlight and WPF applications.