C# add new text strings after the searched text string in word document

With Spire.Doc for .NET, we can easily insert new text to word document at exact position, it also supports to insert new text after the certain text strings at many places. This article will show you how to insert new text strings after the searched text string in word document.

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace Word
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the sample document
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx", FileFormat.Docx2010);

            //find all the text string “New Zealand” from the sample document
            TextSelection[] selections = doc.FindAllString("New Zealand", true, true);
            int index = 0;

            //defines text range
            TextRange range = new TextRange(doc);


            //insert new text string (NY) after the searched text string
            foreach (TextSelection selection in selections)
            {
                range = selection.GetAsOneRange();
                TextRange newrange = new TextRange(doc);
                newrange.Text = ("(NY)");
                index = range.OwnerParagraph.ChildObjects.IndexOf(range);
                range.OwnerParagraph.ChildObjects.Insert(index + 1, newrange);

            }

            //find and highlight the newly added text string NY
            TextSelection[] text2 = doc.FindAllString("NY", false, true);
            foreach (TextSelection seletion in text2)
            {
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
            }

            //save the document 
            doc.SaveToFile("Result.docx", FileFormat.Docx2010);
        }
    }
}

Effective screenshot after adding the text strings to the searched text:

C# add new text strings after the searched text string in word document