Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if string begins with a string?

Tags:

vba

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?

like image 981
armstrhb Avatar asked Dec 27 '13 15:12

armstrhb


People also ask

How do you check if a string starts with a string in Python?

Python String startswith()The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .

How do you check if a string starts with a string in Java?

Java String startsWith() Method The startsWith() method checks whether a string starts with the specified character(s). Tip: Use the endsWith() method to check whether a string ends with the specified character(s).

How do you check if a string starts with a word?

We can use the startsWith() method of String class to check whether a string begins with a specific string or not, it returns a boolean, true or false.

How do you check if a string starts with a letter?

Check if String starts with a Letter using isapha() In Python, the string class provides a function isalpha(). It returns True if all the characters in the string are alphabetic and at least one character in the string. We can use this to check if a string starts with a letter.


2 Answers

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:

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").

Like

You can also use the like comparison operator along with some basic pattern matching:

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.

like image 106
armstrhb Avatar answered Oct 02 '22 18:10

armstrhb


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:

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:

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 
like image 20
Blackhawk Avatar answered Oct 02 '22 18:10

Blackhawk