实例048文本查找与替换

Strings.InStr 方法

https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.visualbasic.strings.instr?redirectedfrom=MSDN&view=netframework-4.8#overloads

返回一个整数,该整数指定一个字符串在另一个字符串中的第一个匹配项的起始位置。 如果找到了匹配项,则该整数是从 1 开始的索引。 如果未找到匹配项,则函数返回零。

控件属性控件属性
TextBoxNametxtTextButtonNamebtnSearch
 Multilinetrue Text查找
 HideSelectionFalseButtonNamebtnRaplace
 Size288,232 Text替换
 Location0,0ButtonNamebtnExit
    Text退出
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        txtText.Text = "Hello,how are you."
    End Sub

    Public Function FindWord(ByVal substring As String) As Boolean
        Dim TextString As String = txtText.Text
        If substring.Equals("") Then
            Return False
        End If
        Dim StartPosition As Integer
        StartPosition = InStr(TextString, substring)
        If StartPosition > 0 Then
            txtText.SelectionStart = StartPosition - 1
            txtText.SelectionLength = Len(substring)
            Return True
        Else
            Return False
        End If

    End Function


    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Dim results As Boolean
        Dim substring As String
        substring = Trim(InputBox("输入要查找的字符串", "查找", txtText.SelectedText))
        If substring.Equals("") Then
            Exit Sub
        End If
        MsgBox("要查找的字符串是:" & substring)
        results = FindWord(substring)
        If Not results Then
            MsgBox("文本框中没有要找的字符串")
        End If
    End Sub

    Private Sub btnReplace_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReplace.Click
        Dim result As Boolean
        Dim substring As String
        If txtText.SelectedText.Equals("") Then
            substring = Trim(InputBox("输入要查找的字符串", "替换", txtText.SelectedText))
            result = FindWord(substring)
            If Not result Then
                MsgBox("文本框中没有要找的文本")
                Exit Sub
            End If
        End If
        substring = Trim(InputBox("把找到的文本替换为", "替换", txtText.SelectedText))
        If substring.Equals("") Then
            Exit Sub
        End If
        txtText.SelectedText = substring
    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub
End Class

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ngbshzhn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值