2017-06-11 21 views
-1

我做的,從數字ASCII值以下轉化爲各自的字符在Visual Basic中,悲慘的失敗了:「的Visual Basic 2015」轉換ASCII到字符,但未能爲什麼

在這裏,在PTH給出的數值已轉換將Ascii的值,以便在可變textval變量所看到的是該路徑的ASCII equivalint

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)第二個字符是一個冒號的任何值「:」或ascii number 2961

如何解決此問題並使其更具普遍性,以便接收任何特殊字符?

在此先感謝您的寶貴答案。

+0

你在這裏沒有做任何轉換。你只是在空格處分割一個字符串。 – GSerg

+0

您需要'Chr'將int從字符轉換爲字符。 –

+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 
+0

如果輸入無效,這將引發異常。 – dbasnett

+0

我不明白爲什麼這個真正的問題被降級時,答案是如此完美是由@SebastianBrosch給出很多感謝您的答案這項工程100%請有人upvote這個問題,而不是-2 –

+0

我喜歡你的解決方案@塞巴斯蒂安布羅什都與這個問題有關。 –

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

如果您正在尋找一個通用的「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