简体   繁体   English

在vbs中比较两个字符串时,修剪功能不会删除字符串末尾的空格

[英]Trim function does not remove spaces at end of a string while comparing two strings in vbs

I have a simple script which takes two strings and compare them. 我有一个简单的脚本,需要两个字符串并进行比较。 The first one has a space at the end and the second does not have that. 第一个在末端有一个空格,第二个没有该空格。

Function compare(str1,str2)
 dim a 
 If strComp(trim(str1),trim(str2))=0 Then 
     msgbox "OK"
     a=1  
 Else
     msgbox "KO" 
     a=0
 End If    

 compare=a

End Function

I use this function in this way: 我以这种方式使用此功能:

s1=     SUCCESSFULLY CONNECTED
s2=     SUCCESSFULLY CONNECTED
result=compare(s1,s2)

The difference between s1 and s2 is that s1 ends with a single space while s2 does not have any space at the end. s1和s2之间的区别在于s1以单个空格结尾,而s2末尾没有空格。 This why I use the Trim function to ignore that space. 这就是为什么我使用Trim函数忽略该空间的原因。 Despite that, for s1 and s2, I always get the message "KO" in dialog box. 尽管如此,对于s1和s2,我总是在对话框中收到消息“ KO”。 I have even changed the condition by 我什至改变了情况

If trim(str1)=trim(str2) Then

But popup is still returned "KO". 但是弹出窗口仍然返回“ KO”。 This is a wonderful situation! 这是一个奇妙的情况!

Please, I'm tired of that and hope that you help understand this situation. 拜托,我对此感到厌倦,并希望您能帮助您了解这种情况。 Thank you in advance 先感谢您

VBScript's Trim removes spaces/blanks, not other kinds of whitespace. VBScript的Trim删除空格/空格,而不是其他种类的空格。 You'll need a RegExp to clean strings with leading/trailing vbTab, vbCrLf, ... which you often get, when you process the output of .Run or. 在处理.Run或输出时,通常需要使用RegExp来使用前导/后缀vbTab,vbCrLf等清理字符串。 Exec. Exec的。

Demo snippet: 演示片段:

>> s1 = "abc" & vbCrLf & " "
>> s2 = "abc"
>> WScript.Echo Len(s1), Len(s2)
>> set r = New RegExp
>> r.Global = True
>> r.Pattern = "^\s+|\s+$"
>> s1 = r.Replace(s1, "")
>> s2 = r.Replace(s2, "")
>> WScript.Echo Len(s1), Len(s2)
>> WScript.Echo CStr(s1 = s2)
>>
6 3
3 3
True

You might like to try this: 您可能想尝试以下方法:

Dim str1, str2
str1 = "help"
str2 = "Me"
WScript.Echo str1 & str2
str1 = str1 & vbTab
WScript.Echo str1 & str2
WScript.Echo len(str1) & " " & len(str2)
If Right(str1,1) = vbTab Then
    WScript.Echo left(str1,Len(str1) - 1) & str2
Else
    WScript.echo "Oops"
End If

Note that the trailing vbTab added to str1 is now removed simply by removing the last character. 请注意,现在只需删除最后一个字符即可删除添加到str1的结尾vbTab。

This is useful if you want to preserve the inner VbTabs if you were going to use them to split the string into an array, for example. 例如,如果要使用内部VbTab将字符串拆分为数组,则此功能非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM