从 VBA 中的字符串中修剪空字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3170220/
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
Trim null characters from a string in VBA
提问by BenV
I'm calling a Win32 API function and getting back a string padded with null characters. Trim$()
doesn't remove them. Is there an easier solution then removing them one character at a time?
我正在调用一个 Win32 API 函数并取回一个用空字符填充的字符串。 Trim$()
不会删除它们。有没有比一次删除一个字符更简单的解决方案?
回答by Don Dickinson
if it's just padded to the right, you can use something like this:
如果它只是填充到右边,你可以使用这样的东西:
function ntrim(byval theString as string) as string
dim iPos as long
iPos = instr(theString, chr$(0))
if iPos > 0 then theString = left$(theString, iPos - 1)
ntrim = theString
end function
回答by JonTheNiceGuy
Loosely based on the last one, maybe this might be better if there's a risk you might have NULLs in your text for some other reason?
松散地基于最后一个,如果由于其他原因,您的文本中可能存在 NULL 的风险,也许这可能会更好?
Function nTrim2(theString As String) As String
Dim iPos As Long
iPos = Len(theString)
For i = iPos To 0 Step -1
iPos = i
If Mid$(theString, i, 1) <> Chr$(0) Then Exit For
Next
nTrim2 = Left$(theString, iPos)
End Function
回答by darekk
In my case Replace() and InStr() don't work with Chr(0) (can't see it not displaying any error), but Nulls can be removed comparing and using Mid(), Left() and Len() as above or in this example:
在我的情况下,Replace() 和 InStr() 不适用于 Chr(0)(看不到它没有显示任何错误),但是可以通过比较和使用 Mid()、Left() 和 Len() 来删除空值如上所述或在此示例中:
If Mid$(str, 1, 1) = Chr$(0) Then str = Mid$(str, 2)
If Mid$(str, Len(str), 1) = Chr$(0) Then str = Left$(str, Len(str) - 1)
This is Null removal from ends, for example from objFile.ExtendedProperty("Dimensions")
value, like "?600 x 400?". Nulls (?) are insterted here in Windows 10 but not in Windows XP.
这是从末端移除空objFile.ExtendedProperty("Dimensions")
值,例如从值中移除,如“?600 x 400?”。空值 (?) 在 Windows 10 中插入此处,但在 Windows XP 中未插入。