“Visual Basic 2015”将Ascii转换为Character失败的原因

时间:2017-06-11 10:25:42

标签: vb.net visual-studio-2015 ascii implicit-conversion

我正在进行以下从Numeric Ascii值到Visual Basic中各自字符的转换,但它失败了:

此处pth中给出的值已经转换为Ascii值,因此您在变量textval变量中看到的是路径的ascii等值

    Dim i As Integer
    Dim dec As String
    Dim original As Integer
    Dim sentence As String
    Dim inter As String
    Dim pth =" c:\TESTER:\JESTER\MESTER "
    textval="32 99 58 92 84 69 83 84 69 82 58 92 74 69 83 84 69 82 92 77 69 83 84 69 82 32"
    textval = Trim(textval)
    'Dim ts() As String = Split(textval)
    Dim words As String() = textval.Split(New Char() {" "c})
    Label1.Text = words(0) + words(1) + words(2)
    original = Int(ts(2))

上面的代码没有给出单词(2)的任何值,第二个字符是COLON“:”或ascii数字2961

如何更正此问题并使其更具普遍性,以便采用任何特殊字符?

提前感谢您的宝贵答案。

3 个答案:

答案 0 :(得分:2)

您不能将整数值转换为字符。您必须使用Chr or ChrW来解决此问题。请参阅以下代码示例:

使用Chr的解决方案:

Dim textValues1 As String = "32 99 58 92 84 69 83 84 69 82 58 92 74 69 83 84 69 82 92 77 69 83 84 69 82 32"
textValues1 = textValues1.Trim
Dim textWords1 As String() = textValues1.Split(New Char() {" "c})
Dim strValue1 As String = ""

For i As Integer = 0 To UBound(textWords1)
    Dim numValue As Integer = 0

    If Integer.TryParse(textWords1(i), numValue) Then
        strValue1 &= Chr(CInt(numValue))
    End If
Next

Debug.Print(strValue1) 'output:  c:\TESTER:\JESTER\MESTER 

使用ChrW的解决方案:

Dim textValues2 As String = "32 99 58 92 84 69 83 84 69 82 58 92 74 69 83 84 69 82 92 77 69 83 84 69 82 32"
textValues2 = textValues2.Trim
Dim textWords2() As String = textValues2.Split(New Char() {" "c})
Dim strValue2 As String = ""

For j As Integer = 0 To UBound(textWords2)
    Dim numValue As Integer = 0

    If Integer.TryParse(textWords2(j), numValue) Then
        strValue2 &= ChrW(CInt(numValue))
    End If
Next

Debug.Print(strValue2) 'output: c:\TESTER:\JESTER\MESTER 

答案 1 :(得分:2)

此代码应该为您提供想法。请注意,整数表示的字符串值在转换之前会被验证为整数。

    Dim textval As String = "32 a 99 58 92 84 69 83 84 69 82 58 92 74 69 83 84 69 82 92 77 69 83 84 69 82 32"
    Dim cvals As New List(Of Char)

    For Each s As String In textval.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
        Dim ival As Integer
        If Integer.TryParse(s, ival) Then
            cvals.Add(ChrW(ival))
        End If
    Next

    Dim cv As String = cvals.ToArray ' c:\TESTER:\JESTER\MESTER 

此方法验证输入是否有效。

答案 2 :(得分:2)

如果您正在寻找一个通用的" Visual studio 2015"然后回答使用.Net Framework的现有功能。请考虑以下语句将字符串转换为字节或字符:

Dim bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(pth)
Dim chars = System.Text.ASCIIEncoding.ASCII.GetChars(bytes)
Dim stringValue = System.Text.ASCIIEncoding.ASCII.GetString(bytes)

如果涉及特殊字符,您也可以使用其他编码,如UTF8和Unicode。这是指向文档的链接:https://msdn.microsoft.com/en-us/library/system.text.asciiencoding(v=vs.110).aspx