vb.net 教程 4-7 文本文件编码 2

前端之家收集整理的这篇文章主要介绍了vb.net 教程 4-7 文本文件编码 2前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本节将用一个简单的例子来说明文本编码:


窗体设计如下:

comboBox中的数据:

请引用 System.Text

Imports System.Text

当按下“生成”按钮时的代码

    Private Sub btnChange_Click(sender As Object,e As EventArgs) Handles btnChange.Click
        Dim enc As Encoding
        Select Case cbEncode.Text
            Case "ASCII"
                enc = Encoding.ASCII
            Case "Unicode"
                enc = Encoding.Unicode
            Case "UTF32"
                enc = Encoding.UTF32
            Case "UTF7"
                enc = Encoding.UTF7
            Case "UTF8"
                enc = Encoding.UTF8
            Case "GB2312"
                enc = Encoding.GetEncoding("gb2312")
            Case "big5"
                enc = Encoding.GetEncoding("big5")
        End Select


        Dim byteSource() As Byte = enc.GetBytes(txtSource.Text)

        Dim strEnc As String = ""
        For i As Integer = 0 To byteSource.Length - 1
            strEnc &= Convert.ToString(byteSource(i),16).ToUpper & " "
        Next
        txtDest.Text &= "编码方式:" & enc.EncodingName & "编码结果:" & strEnc & vbCrLf
    End Sub

运行结果:

可以看到ASCII不支持繁体 "無" 字,返回的是3F(十进制:63),查找ASCII表,可知,返回的是“?”。

同样,Big5不支持简体的“无”字,返回的也是3F。


简单的测试将字节数组编码成字符:

    Private Sub Button1_Click(sender As Object,e As EventArgs) Handles Button1.Click
        Dim byteSource() As Byte
        ReDim byteSource(1)
        '無
        byteSource(0) = 181  '=>B5
        byteSource(1) = 76   '=>4C

        Dim enc As Encoding
        enc = Encoding.GetEncoding("big5")
        Dim strDest As String
        strDest = enc.GetString(byteSource)
        txtSource.Text = strDest
    End Sub


由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。

学习更多vb.net知识,请参看 vb.net 教程 目录

原文链接:https://www.f2er.com/vb/256535.html

猜你在找的VB相关文章