arrays - 从字符数组转换时的字符串长度

标签 arrays .net string vb.net

我在字符串处理方面遇到严重问题。 由于我的问题很难描述,我将从一些演示代码开始重现它们:

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                    

结果消息框如下所示:

screenshot of the messagebox showing only hi != hi but not the rest of the text

此比较失败的原因是 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 个:

enter image description here

其余的都是 null/Nothing,对于 Char 来说意味着 Chr(0)NUL。由于 NUL 用于标记 String 的结尾,因此只有 NUL 之前的字符才会在 Console 中打印code>、MessageBox 等。附加到字符串的文本也不会显示。

<小时/>

概念

由于上面的字符串是直接从 char 数组创建的,因此长度是原始数组的长度。 Nul 是有效的 char,因此它们会添加到字符串中:

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)
<小时/>

字符串可以作为字符数组进行索引/迭代:

    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

这不会编译,因为它们是只读的。

另请参阅:

ASCII table

关于arrays - 从字符数组转换时的字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24398217/

相关文章:

arrays - 输出mongoose中的所有文档

python - 二进制 numpy 数组之间的快速操作

java - "Encode"数组中的整数通过给定的方案转换为字符

javascript - jQuery inArray 和 Javascript IndexOf 返回部分匹配。我需要检查完整匹配

.net - 是否可以合并 Lucene.NET 索引

java - java - 如何在不考虑空格的情况下比较java中的两个字符串?

python - 通过特定分隔符进行字符串操作并写入文本文件

python - 用 pandas 替换字符串

c# - 将 Ajax 数组发送到 Controller

c# - 如何在动态生成的C#代码中初始化各种类型变量?