翻譯|使用教程|編輯:李顯亮|2021-01-18 10:27:21.153|閱讀 361 次
概述:在本文中,將學習如何在C ++應用程序中查找和替換Word文檔中的文本。當需要一次性替換多個文檔中的特定文本時,這可能會很有用。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
查找和替換是MS Word提供的一項有用功能,可以一次更新所有出現的特定文本。因此,不必手動查找和替換整個文檔中的文本。
在本文中,將學習如何在C ++應用程序中查找和替換Word文檔中的文本。當需要一次性替換多個文檔中的特定文本時,這可能會很有用。
Aspose.Words for C ++是一個C ++庫,用于創建新的和處理現有的Word文檔。該API支持廣泛的基本和高級Word自動化功能。
如果你還沒有用過C ++版Aspose.Words可以點擊這里下載最新版測試。
以下是使用Aspose.Words for C ++在Word文檔中查找和替換文本的步驟。
下面的代碼示例演示如何使用C ++在Word文檔中查找“ sad”并將其替換為“ bad”。
// Load MS Word document System::SharedPtrdoc = System::MakeObject(u"Document.doc"); // Find and replace the text doc->get_Range()->Replace(u"sad", u"bad", System::MakeObject(FindReplaceDirection::Forward)); // Save the updated document doc->Save(u"updated.doc");
可以定義正則表達式,以查找和替換遵循特定模式的單詞。例如,您可以將單詞“ sad”和“ mad”替換為“ bad”。以下是在Word文檔中查找和替換與正則表達式匹配的單詞的步驟。
下面的代碼示例演示如何在C ++中使用正則表達式查找和替換文本。
// Load MS Word document System::SharedPtrdoc = System::MakeObject(u"Document.doc"); // Create find and replace options System::SharedPtroptions = System::MakeObject(); // Find and replace the text doc->get_Range()->Replace(System::MakeObject(u"[s|m]ad"), u"bad", options); // Save the updated document doc->Save(u"updated.doc");
在某些情況下,您要替換的文本可能包含換行符,即換行符,段落換行符,分節符等。為了應對這種情況,Aspose.Words for C ++在搜索和替換字符串中支持以下元字符。
下面的代碼示例演示如何使用Word文檔中的元字符查找和替換文本。
// Load MS Word document System::SharedPtrdoc = System::MakeObject(u"Document.doc"); // Create find and replace options System::SharedPtroptions = System::MakeObject(); // Find and replace the text doc->get_Range()->Replace(u"This is Line 1&pThis is Line 2", u"This is replaced line", options); doc->get_Range()->Replace(u"This is Line 1&mThis is Line 2", u"Page break is replaced with new text.", options); // Save the updated document doc->Save(u"updated.doc");
Aspose.Words for C ++還允許您在查找和替換操作期間忽略字段和修訂中的文本。該FindReplaceOptions類,您可以指定選項來添加這個定制。FindReplaceOptions類提供以下方法來在不同情況下忽略文本:
下面的代碼示例演示如何在上述每種情況下忽略文本。
// Load MS Word document System::SharedPtrdoc = System::MakeObject(u"Document.doc"); // Create find and replace options System::SharedPtroptions = System::MakeObject(); // Replace 'e' in document ignoring text inside field options->set_IgnoreFields(true); doc->get_Range()->Replace(System::MakeObject(u"e"), u"*", options); // Replace 'e' in document ignoring deleted text options->set_IgnoreDeleted(true); doc->get_Range()->Replace(System::MakeObject(u"e"), u"*", options); // Replace 'e' in document ignoring inserted text options->set_IgnoreInserted(true); doc->get_Range()->Replace(System::MakeObject(u"e"), u"*", options); // Save the updated document doc->Save(u"updated.doc");
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn