如何将字符串复制到字节数组
我有一个充满文本行的 StringArray,我需要获取每个字符串数组并将它们转换为字节。一旦
Dim splitText() As String = TextRead.Split(Chr(13))
Dim byteArray() as string = Byte.Parse(splitText(0))
我可以将字符串数组的一个元素转换为字节,我将为字符串数组中的每个位置放置一个循环,但它表示字符串格式对于 byte.parser 来说不正确。
I have a StringArray that is filled with line of text and I need to take each array of strings and convert them to byte. How
Dim splitText() As String = TextRead.Split(Chr(13))
Dim byteArray() as string = Byte.Parse(splitText(0))
once I can get one element of the string array to convert to Byte I will put a loop around it for each position in the string array but it says the string format is not correct for the byte.parser.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
换行符很少是单个
CR
字符,它几乎仅由旧的 Macintosh 系统(即版本 9 及更早版本)使用。常见的换行符是CR+LF
(Windows) 和LF
(Unix/OS X)。如果在错误的换行符上分割字符串,则最终整个字符串将作为数组中的单个项目不受影响,或者在字符串中留下一半换行符。无论哪种方式,您都将无法解析字符串。
对于具有 Windows 类型换行符的字符串:
对于具有 Unix/OS X 类型换行符的字符串:
处理两种换行符:
使用当前系统的换行符:
例如,如果字符串包含十进制格式的数字
13{break}37{break}42
,您现在可以将字符串解析为字节:全部作为单行代码:
A line break is rarely a single
CR
character, that's almost only used by the old Macintosh systems, i.e. version 9 and older. The common line breaks areCR+LF
(Windows) andLF
(Unix/OS X).If you split the string on the wrong line break, you will either end up with the entire string unaffected as a single item in the array, or leave half of the line break characters in the strings. Either way you won't be able to parse the strings.
For a string with Windows type line breaks:
For a string with Unix/OS X type line break:
To handle both kinds of line breaks:
To use the line break of the current system:
If the string contains numbers in decimal format, for example
13{break}37{break}42
, you will now be able to parse the strings into bytes:All as a one-liner:
看起来您正在尝试解析整行文本,而不是单个字节。为了完成您想要做的事情,您需要循环遍历字符串中的每个字符并将其解析为一个字节。但是,您可能会发现使用内置的 .NET 解析方法将字符串转换为字节,而不是采取漫长的路线。例如,
您可以更改编码方法(根据您的要求),在本例中我使用的是 UTF8。
附带说明一下,您还可以使用
GetString
将整个字节数组反转为字符串,该方法与GetBytes
位于同一类中。It looks like you are attempting to parse an entire line of text, instead of a single byte. In order to accomplish what you are attempting to do, you'd need to loop through each character in your string and parse it into a byte. However, instead of taking the long route, you may find use to use the built in .NET parsing methods for string to bytes. e.g.
You can change up the encoding method (depending on your requirements), as in this example I am using UTF8.
As a side note, you can also reverse an entire byte array to a string using
GetString
, found in the same class asGetBytes
.你试过吗
have you tried