我想比较一个字符串是否包含另一个字符串的所有字符。
示例:
字符串1 Hejslclo
字符串2 你好
True string 2包含字符串1的所有字符。
我已将字符串1转换为数组,我认为应该有一个循环来检查使用Instr
我的第一次尝试:
Sub StringintoArray()
Dim Temp As String
Dim MyString As String
Dim String2 As String
MyString = "Heaslsflo"
String2 = "Hello"
Temp = StrConv(MyString, vbUnicode)
Temp = Left(Temp, Len(Temp) - 1)
aLetter = Split(Temp, Chr(0))
'Dim StartRow As Integer
Dim i As Integer
For i = 0 To L(Temp)
If InStr(i, String2, aLetter(I)) <> 0 Then
MsgBox ("Yes")
Else
MsgBox ("No")
End If
Next i
End Sub
答案 0 :(得分:2)
好的 - 我觉得无聊而且有点儿。看看你的代码,你几乎就在那里。 认为这应该做你想做的事情
Option Explicit
Public Function CompareStrings(string1 As String, string2 As String) As Boolean
Dim i As Long, j As Long, k As Long
Dim arr1 As Variant, arr2 As Variant
' Set to default
CompareStrings = False
' Split strings into arrays
arr1 = Split(StrConv(string1, vbUnicode), Chr(0))
arr2 = Split(StrConv(string2, vbUnicode), Chr(0))
' Initialise counter
k = 0
' Loop over both arrays
For i = LBound(arr2) To UBound(arr2)
For j = LBound(arr1) To UBound(arr1)
If LCase(arr2(i)) = LCase(arr1(j)) Then
k = k + 1
Exit For
End If
Next j
Next i
' Test if counter is equal to array length and set answer if so
If k - 1 = UBound(arr2) Then CompareStrings = True
End Function
Public Sub TestComparison()
Dim string1 As String, string2 As String
string1 = "Hello"
string2 = "Hejslclo"
If CompareStrings(string1:=string1, string2:=string2) Then
Debug.Print string1; " contains "; string2
Else
Debug.Print string1; " does not contain "; string2
End If
End Sub