翻譯|使用教程|編輯:李顯亮|2021-01-18 10:27:21.153|閱讀 361 次
概述:在本文中,將學(xué)習(xí)如何在C ++應(yīng)用程序中查找和替換Word文檔中的文本。當(dāng)需要一次性替換多個(gè)文檔中的特定文本時(shí),這可能會(huì)很有用。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關(guān)鏈接:
查找和替換是MS Word提供的一項(xiàng)有用功能,可以一次更新所有出現(xiàn)的特定文本。因此,不必手動(dòng)查找和替換整個(gè)文檔中的文本。
在本文中,將學(xué)習(xí)如何在C ++應(yīng)用程序中查找和替換Word文檔中的文本。當(dāng)需要一次性替換多個(gè)文檔中的特定文本時(shí),這可能會(huì)很有用。
Aspose.Words for C ++是一個(gè)C ++庫,用于創(chuàng)建新的和處理現(xiàn)有的Word文檔。該API支持廣泛的基本和高級(jí)Word自動(dòng)化功能。
如果你還沒有用過C ++版Aspose.Words可以點(diǎn)擊這里下載最新版測試。
以下是使用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");
可以定義正則表達(dá)式,以查找和替換遵循特定模式的單詞。例如,您可以將單詞“ sad”和“ mad”替換為“ bad”。以下是在Word文檔中查找和替換與正則表達(dá)式匹配的單詞的步驟。
下面的代碼示例演示如何在C ++中使用正則表達(dá)式查找和替換文本。
// 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");
在某些情況下,您要替換的文本可能包含換行符,即換行符,段落換行符,分節(jié)符等。為了應(yīng)對(duì)這種情況,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類,您可以指定選項(xiàng)來添加這個(gè)定制。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");
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn