由于我的问题很难描述,我将从一些演示代码开始再现它们:
Dim s1 As String = "hi" Dim c(30) As Char c(0) = "h" c(1) = "i" Dim s2 As String = CStr(c) s2 = s2.Trim() If not s1 = s2 Then MsgBox(s1 + " != " + s2 + Environment.NewLine + _ "Anything here won't be printed anyway..." + Environment.NewLine + _ "s1.length: " + s1.Length.ToString + Environment.NewLine + _ "s2.length: " + s2.Length.ToString + Environment.NewLine) End If
结果消息框如下所示:
这种比较失败的原因是s2的长度为31(来自原始数组大小),而s1的长度为2.
当从字节数组中读取字符串信息时,我经常偶然发现这种问题,例如,当处理来自MP3的ID3Tags或其他具有预定长度的编码(ASCII,UTF8,…)信息时.
是否有任何快速而干净的方法来防止这个问题?
将s2“修剪”为调试器显示的字符串的最简单方法是什么?
提前致谢,
贾尼斯
解决方法
Dim myChars(30) As Char myChars(0) = "h"c ' cannot convert string to char myChars(1) = "i"c ' under option strict (narrowing) Dim myStrA As New String(myChars) Dim myStrB As String = CStr(myChars)
简短的回答是这样的:
在引擎盖下,字符串是字符数组.最后两行都使用NET代码创建一个字符串,另一个使用VB函数.问题是,虽然数组有31个元素,但只有2个被初始化:
其余为null / Nothing,对于Char,意味着Chr(0)或NUL.由于NUL用于标记String的结尾,因此只有NUL之前的字符才会在Console,MessageBox等中打印.附加到字符串的文本也不会显示.
概念
由于上面的字符串是直接从char数组创建的,因此长度是原始数组的长度. Nul是一个有效的字符,所以它们被添加到字符串中:
Console.WriteLine(myStrA.Length) ' == 31
那么,为什么Trim不删除nul字符呢? MSDN(和Intellisense)告诉我们:
[Trim] Removes all leading and trailing white-space characters from the current String object.
尾随null / Chr(0)字符不是Tab,Lf,Cr或Space等空格,而是control character.
但是,String.Trim
有一个重载,允许您指定要删除的字符:
myStrA = myStrA.Trim(Convert.ToChar(0)) ' using VB namespace constant myStrA = myStrA.Trim( Microsoft.VisualBasic.ControlChars.NullChar)
您可以指定多个字符:
' nuls and spaces: myStrA = myStrA.Trim(Convert.ToChar(0)," "c)
字符串可以作为char数组索引/迭代:
For n As Int32 = 0 To myStrA.Length Console.Write("{0} is '{1}'",n,myStrA(n)) ' or myStrA.Chars(n) Next
0 is ‘h’
1 is ‘i’
2 is ‘
(输出窗口甚至不会打印尾随的CRLF.)但是,您无法更改字符串的char数组来更改字符串数据:
myStrA(2) = "!"c
这不会编译,因为它们是只读的.
也可以看看:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。