繁体   English   中英

VB.NET:在for循环中将字符串转换为dec

[英]VB.NET: Convert string to dec in a for-loop

因此,我想从此表中将字符串转换为dec值: http : //en.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange#ASCII-Table

例如, "hello"应为104101108108111然后(h = 104,e = 101 ...)。 好吧,我必须为此使用一个for循环,但似乎无法得到错误。

Private Function function1(text As String)
    Dim dec As String
    Dim i As Integer = 0

    For i = 0 To text.Length
        dec = dec & System.Text.ASCIIEncoding.ASCII.GetBytes(text)(i)
        i += 1
    Next
    Return dec
End Function

它可以工作,但是如果“文本”的长度是偶数(例如,文本有2、4、6或8个字母),则会给我一个错误。 并且当它不均匀时(文本有1、3、5、7个字母),它只会转换这些不均匀的字母。 因此,仅作为示例。 “ hello”的长度不均匀(5个字母)。 因此,它不会给我一个错误。 大! 但是,它仅将“ h”,第一个“ l”和“ o”转换为dec。

谁能解释我为什么以及如何解决这个问题?

您正在循环中增加计数i 您无需在For循环中执行此操作。

另外,您将经过字符串的末尾。 您需要以Length - 1结束循环

Private Function function1(text As String) As String
    Dim dec As String = ""
    For i As Integer = 0 To text.Length - 1
        dec = dec & System.Text.ASCIIEncoding.ASCII.GetBytes(text)(i)
    Next
    Return dec
End Function

注意:严格启用选项-从长远来看,您一定会很高兴!

循环自身增加,不增加。 它是从零开始的数组,因此14长度的文本为0 to 13

Private Function function1(text As String)
 Dim dec As String = ""
 For i As Integer = 0 To text.Length - 1
    dec = dec & System.Text.ASCIIEncoding.ASCII.GetBytes(text(i))(0)
    'i += 1 omit this part
 Next
 Return dec
End Function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM