Strings.InStr 方法
返回一个整数,该整数指定一个字符串在另一个字符串中的第一个匹配项的起始位置。 如果找到了匹配项,则该整数是从 1 开始的索引。 如果未找到匹配项,则函数返回零。
控件 | 属性 | 值 | 控件 | 属性 | 值 |
TextBox | Name | txtText | Button | Name | btnSearch |
Multiline | true | Text | 查找 | ||
HideSelection | False | Button | Name | btnRaplace | |
Size | 288,232 | Text | 替换 | ||
Location | 0,0 | Button | Name | btnExit | |
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