如果字符串开头的字符串测试?

问题描述 投票:60回答:2

在VBA中,什么是测试一个字符串的子串开头的最直接的方法是什么? Java有startsWith。是否有一个VBA等同?

vba
2个回答
116
投票

做这件事有很多种方法:

InStr函数

您可以使用InStr内建函数测试字符串包含的子字符串。 InStr或者返回索引的第一个比赛,或者0。所以,你可以,如果一个字符串,通过执行以下操作的子测试开始:

If InStr(1, "Hello World", "Hello W") = 1 Then
    MsgBox "Yep, this string begins with Hello W!"
End If

如果InStr返回1,那么字符串( “Hello World” 的),始于子( “你好W”)。

喜欢

您也可以使用like比较操作一些基本的模式匹配一​​起:

If "Hello World" Like "Hello W*" Then
    MsgBox "Yep, this string begins with Hello W!"
End If

在这方面,我们使用星号(*),以测试是否字符串与我们的子开始。


34
投票

declaration and description of the startsWith Java function来看,“最直接的方式”来实现它在VBA要么与Left

Public Function startsWith(str As String, prefix As String) As Boolean
    startsWith = Left(str, Len(prefix)) = prefix
End Function

或者,如果你想拥有可用的偏移参数,以Mid

Public Function startsWith(str As String, prefix As String, Optional toffset As Integer = 0) As Boolean
    startsWith = Mid(str, toffset + 1, Len(prefix)) = prefix
End Function
© www.soinside.com 2019 - 2024. All rights reserved.