VB应用程序中实现“查找和替换”功能
5180 点击·0 回帖
![]() | ![]() | |
![]() | 一、前言 尽管VisualBasic并不是我最喜欢的开发工具,但我喜欢它简单而又丰富的库集。每当开发一个需要处理大量文本数据的应用程序时,需要具有拼写错误纠正功能,例如,微软的word程序,当运行"拼写检查"时,将提供给你一个改正错误的机会(尽管是建议),它同时也提供了"查找替换"工具,用以进行用户定义的单词替换。这篇文章我将解释如何在VB应用程序中实现"查找替换"功能。 二、前提条件 在解释代码的时候,我假定读者朋友们已经有使用VisualBasic的经验,熟悉VisualStudio开发环境中各种内置的控件及库函数(尽管我使用的不多)。我已经尝试着尽可能地简化程序代码,用不了多久你就可以明白程序的逻辑。如果想对一些库函数(如参数,语法)进一步详细地理解,可以参阅MSDN。图一是程序运行后的效果图: -> ->;Edit ...;FindandReplacemnuFindandreplace E;xitmnuExit-> 向默认窗体添加一个TextBox控件,命名为txtClientArea。使用鼠标调整控件位置和尺寸,使它覆盖窗体的整个客户区,在属性窗口将这个TextBox控件的MultiLine属性设置为"True"。 使用Project>AddForm菜单向工程中添加另外一个窗体,将这个窗体命名为"frmFindReplace",并在属性窗口中将它的BorderStyle属性设置为"4-FixedToolWindow"。现在,添加两个TextBox控件,并分别命名为"txtSearchTerm"和"txtReplaceWithString"。添加一个复选框,命名为chkCaseSense。最后,添加一个命令按钮控件,命名为"cmdReplace"。 在frmMainForm窗体中添加如下代码: ->PrivateSubmnuExit_Click() End EndSub PrivateSubmnuFindandreplace_Click() frmFindReplace.FindnReplacetxtClientArea EndSub-> 从上面代码中可以非常明显地看出,当点击Exit菜单时,我们想终结应用程序,当点击"FindandReplace"菜单时,想通过共用接口frmFindReplace及FindnReplace()方法来激活frmFindReplace窗体。这个公用的接口使查找算法具有普遍性,使用这个接口时,需要提供一个TextBox作为参数(在这里面,搜寻将被执行)。通过使用你自己的TextBox的名字来代替txtClientArea的名字,可以在多个文本框内执行"查找替换"功能,而不用更改代码。"查找和替换"的实现代码主要是在frmFindReplace窗体内,这个模块的代码如下: ->'Thisvariableisusedformakingthealgorithmgeneric. DimtxtClientAsTextBox 'ThismethodisthepublicinterfacetoSnRfunctionality. PublicSubFindnReplace(ByRefTbAsTextBox) SettxtClient=Tb Me.Show,txtClient.Parent EndSub PrivateSubcmdReplace_Click() DimCaseSenseAsInteger DimSourceTextAsString DimSourceTextCopyAsString DimCntAsInteger 'Checkforthecasesensitivityoptions If(chkCaseSense.Value=vbChecked)Then CaseSense=0 Else CaseSense=1 EndIf 'Onecontainstheoriginaltextandanothercontainsreplaced '(updated)one. 'Usedtocheckwhetherareplacementwasdoneornot. SourceText=txtClient.Text SourceTextCopy=SourceText IfLen(SourceText)=0Then ExitSub EndIf OnErrorGoToErrHandler DimSearchTermLenAsInteger DimFndPosAsInteger SearchTermLen=Len(txtSearchTerm.Text) 'Searchfromthebeginingofthedocument. Cnt=1 'Thisisendlessloop(terminatedonaconditioncheckedinside 'theloopbody). While(1) FndPos=InStr(Cnt,SourceText,txtSearchTerm.Text,CaseSense) 'Whenamatchisfound,replaceitappropriately. If(FndPos>0)Then SourceText=ReplaceFun(SourceText,FndPos,Len(txtSearchTerm.Text),txtReplaceWithString.Text) Cnt=FndPos SearchTermLen Else Cnt=Cnt 1 EndIf 'Whetherareplacementwasdoneatallornot If(Cnt>=Len(SourceText))Then txtClient.Text=SourceText If(SourceTextCopy<>SourceText)Then MsgBox"Finishedreplacingalloccurrences.",vbInformation vbOKOnly,"ReplacedAll" Else MsgBox"Nomatchingstringsfound.Notextreplaced.",vbInformation vbOKOnly,"NoReplacement" EndIf UnloadMe ExitSub EndIf 'ElseRestartfromhenceforth Wend ExitSub ErrHandler: Response=MsgBox("Anerrorocurredwhilesearching.Informthedeveloperwithdetails.",_ vbExclamation vbOKOnly,"ErrorSearching") EndSub PrivateSubForm_Load() 'DefaultSearchTermmustbetheoneselectedbytheuserin 'MainForm IfLen(txtClient.SelText)<>0Then txtSearchTerm.Text=txtClient.SelText EndIf EndSub FunctionReplaceFun(SourceAsString,FromPosAsInteger,_ LengthAsInteger,StringTBReplaced_ AsString)AsString 'Replacesasourcestringwithnewoneappropriately DimResultStrAsString ResultStr=Left(Source,FromPos-1) ResultStr=ResultStr;StringTBReplaced ResultStr=ResultStr;Right(Source,Len(Source)-FromPos-Length 1) ReplaceFun=ResultStr EndFunction PrivateSuBTxtReplaceWithString_Change() CallEnableDisableReplaceButton EndSub PrivateSuBTxtReplaceWithString_GotFocus() 'Selectthecontentsofthetextbox IfLen(txtReplaceWithString.Text)<>0Then txtReplaceWithString.SelStart=0 txtReplaceWithString.SelLength=Len(txtReplaceWithString.Text) EndIf EndSub PrivateSuBTxtSearchTerm_Change() CallEnableDisableReplaceButton EndSub PrivateSubEnableDisableReplaceButton() IfLen(txtSearchTerm.Text)<>0_ AndLen(txtReplaceWithString.Text)<>0Then cmdReplace.Enabled=True Else cmdReplace.Enabled=False EndIf EndSub PrivateSuBTxtSearchTerm_GotFocus() 'Selectthecontentsoftextbox IfLen(txtSearchTerm.Text)<>0Then txtSearchTerm.SelStart=0 txtSearchTerm.SelLength=Len(txtSearchTerm.Text) EndIf EndSub-> | |
![]() | ![]() |