VBS字符串编码转换函数代码
因为业务需要将一些字符串转换为指定编码方便后期操作
核心代码
Const adTypeBinary = 1Const adTypeText = 2' accept a string and convert it to Bytes array in the selected CharsetFunction 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 = NothingEnd Function' accept Bytes array and convert it to a string using the selected charsetFunction 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 = NothingEnd 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
使用例子:
dim s1,s2,FromCharset,ToCharsets1 = "我的字符串之8b8.cn"FromCharset = "GB2312"ToCharset = "ISO-8859-1"s2 = AlterCharset(s1,FromCharset,ToCharset)
VBS字符串编码转换函数代码