vba 测试字符串是否以字符串开头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20802870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test if string begins with a string?
提问by armstrhb
In VBA, what's the most straight forward way to test if a string begins with a substring? Java has startsWith
. Is there a VBA equivalent?
在 VBA 中,测试字符串是否以子字符串开头的最直接方法是什么?Java 有startsWith
. 有VBA等价物吗?
回答by armstrhb
There are several ways to do this:
做这件事有很多种方法:
InStr
指令
You can use the InStr
build-in function to test if a String contains a substring. InStr
will either return the index of the first match, or 0. So you can test if a String begins with a substring by doing the following:
您可以使用InStr
内置函数来测试字符串是否包含子字符串。 InStr
将返回第一个匹配项的索引,或 0。因此,您可以通过执行以下操作来测试字符串是否以子字符串开头:
If InStr(1, "Hello World", "Hello W") = 1 Then
MsgBox "Yep, this string begins with Hello W!"
End If
If InStr
returns 1
, then the String ("Hello World"), begins with the substring ("Hello W").
如果InStr
返回1
,则字符串(“Hello World”)以子字符串(“Hello W”)开头。
Like
喜欢
You can also use the like
comparison operator along with some basic pattern matching:
您还可以使用like
比较运算符以及一些基本的模式匹配:
If "Hello World" Like "Hello W*" Then
MsgBox "Yep, this string begins with Hello W!"
End If
In this, we use an asterisk (*) to test if the String begins with our substring.
在这里,我们使用星号 (*) 来测试字符串是否以我们的子字符串开头。
回答by Blackhawk
Judging by the declaration and description of the startsWith
Java function, the "most straight forward way" to implement it in VBA would either be with Left
:
从Java 函数的声明和描述startsWith
来看,在 VBA 中实现它的“最直接的方法”要么是Left
:
Public Function startsWith(str As String, prefix As String) As Boolean
startsWith = Left(str, Len(prefix)) = prefix
End Function
Or, if you want to have the offset parameter available, with Mid
:
或者,如果您希望偏移参数可用,请使用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