C++でWord文書のテキストを検索して置換する方法

このトピックでは、簡略化されたコード例を使用して、C++でWordドキュメントのテキストを検索して置換する方法を示します。 * C ++を使用することにより、Word文書内のテキストの置換*は、MS Wordまたは相互運用ライブラリに外部依存することなく、数行の簡単なコードで簡単に実行できます。このアプリケーションは、Windows、macOS、またはLinuxプラットフォームで実行されているC++でサポートされている任意のアプリケーションで使用できます。

C++でWord文書のテキストを置き換える手順

  1. NuGetパッケージマネージャーから最新バージョンのAspose.Words.CPPを構成します
  2. Aspose::Words名前空間を含め、必要なヘッダーファイルを追加します
  3. Documentクラスオブジェクトを初期化して、テキストを置き換えるためにDOCXをロードします
  4. FindReplaceOptionsクラスオブジェクトを作成して、さまざまなプロパティを有効にします
  5. 選択した検索のテキスト置換を実行し、文字列を置換します
  6. 置き換えられたテキストを含むWord文書をディスクに保存します

前述の手順では、最初にソースWordドキュメントをディスクからロードし、次にさまざまなプロパティを指定して、検索の基準を設定し、テキストを置換します。これには、方向の置換、大文字と小文字の一致、単語全体の検索などが含まれます。最後に、* C ++を使用してWord文書のテキストを置き換え*、変更したDOCXをディスクに保存します。

C++を使用してWord文書のテキストを置き換えるコード

#pragma once
#include <cstdint>
#include <iostream>
#include <Aspose.Words.Cpp/License.h>
#include <Aspose.Words.Cpp/Document.h>
#include <Aspose.Words.Cpp/Range.h>
#include <Aspose.Words.Cpp/Replacing/FindReplaceOptions.h>
#include <Aspose.Words.Cpp/Replacing/FindReplaceDirection.h>
#include <system/enumerator_adapter.h>
#include <system/io/path.h>
#include <system/smart_ptr.h>
#include <system/shared_ptr.h>
using namespace Aspose::Words;
using namespace Aspose::Words::Replacing;
using System::MakeObject;
using System::SharedPtr;
using System::String;
class FindAndReplaceTextEx
{
public:
static void FindAndReplaceText()
{
// Load and Set API License
System::String LicFilePath = u"Aspose.Total.Net.lic";
SharedPtr<Aspose::Words::License> WordsCPPLicenseForTable = System::MakeObject<Aspose::Words::License>();
// Setting Aspose.Words product license
WordsCPPLicenseForTable->SetLicense(LicFilePath);
// Load an input Word file with Document class for replacing text
SharedPtr<Document> FindInDocument = MakeObject<Document>(u"Test.docx");
// Instantiate FindReplaceOptions class object to replace text string
SharedPtr<FindReplaceOptions> options = MakeObject< FindReplaceOptions>();
options->set_MatchCase(true);
options->set_Direction(FindReplaceDirection::Forward);
options->set_FindWholeWordsOnly(true);
// Apply search and replace string in the Replace method
FindInDocument->get_Range()->Replace(u"Test", u"Replace", options);
// Save the document on disk with replaced text
FindInDocument->Save(u"FindAndReplace.docx");
}
};

この例では、* C ++ Word文書置換テキストの使用は、単純なAPI呼び出しを使用して簡単に実行できます。 * Document class のインスタンスを使用することにより、入力されたWordドキュメントはAPIを使用してロードされます。その後の手順では、 FindReplaceOptionsクラスを使用して、さまざまなプロパティを設定することで検索と置換の条件を設定します。最後に、変更したDOCXをディスクまたはMemoryStreamに出力として保存します。

この記事では、*C++を使用してWord文書内のテキストを検索して置換する方法について説明しました。ただし、WordファイルをPDFにエクスポートする方法については、C++を使用してWordをPDFに変換する方法の記事を参照してください。

 日本語