正文

VBS字符串编码转换函数代码(vb字符串转换为文本类型)墙裂推荐

文章摘要

本文介绍了一个使用ADODB库实现的字符集转换功能,主要包括三个关键函数: 1. **StringToBytes**:接受一个字符串和字符集,将字符串转换为字节数组。通过创建一个文本流,将字符串写入流并转换为目标字符集的字节数组。 2. **BytesToString**:接受字节数组和字符集,将字节数组转换为字符串。通过创建一个二进制流,将字节数组写入流并解码为目标字符集的字符串。 3. **AlterCharset**:通过中间步骤实现字符集转换,首先将字符串转换为字节数组,然后将字节数组转换为目标字符集的字符串。 这些函数利用了ADODB库的Stream对象,通过操作流来实现字符编码的转换。整体上,该方法通过中间字节数组实现了字符集间的转换,适用于需要改变字符集的场景。

Const adTypeBinary=1 Const adTypeText=2 ‘ accept a string and convert it to Bytes array in the selected Charset Function StringToBytes(Str,Charset) Dim Stream : Set Stream=CreateObject(“ADODB.Stream”) Stream.Type=adTypeText Stream.Charset=Charset Stream.Open Stream.WriteText Str Stream.Flush Stream.Position=0 ‘ rewind stream and read Bytes Stream.Type=adTypeBinary StringToBytes=Stream.Read Stream.Close Set Stream=Nothing End Function ‘ accept Bytes array and convert it to a string using the selected charset Function BytesToString(Bytes, Charset) Dim Stream : Set Stream=CreateObject(“ADODB.Stream”) Stream.Charset=Charset Stream.Type=adTypeBinary Stream.Open Stream.Write Bytes Stream.Flush Stream.Position=0 ‘ rewind stream and read text Stream.Type=adTypeText BytesToString=Stream.ReadText Stream.Close Set Stream=Nothing End Function ‘ This will alter charset of a string from 1-byte charset(as windows-1252) ‘ to another 1-byte charset(as windows-1251) Function AlterCharset(Str, FromCharset, ToCharset) Dim Bytes Bytes=StringToBytes(Str, FromCharset) AlterCharset=BytesToString(Bytes, ToCharset) End Function