如果Textbox1.text
包含字符串值ZU4
,如何将该字符串转换为数字ASCII代码,并将其输出到第二个文本框?
我想使用FOR LOOP
条件语句来读取INPUT中的每个字符吗?
样品:
INPUT Textbox1.Text = ZU4
OUTPUT Textbox2.Text = 908552
答案 0 :(得分:1)
你也可以使用LINQ:
TextBox2.Text = String.Join(String.Empty, From c In Textbox1.Text.ToCharArray Select (Asc(c).ToString))
可能对某些求职面试很有用...... :)
答案 1 :(得分:0)
这是C#中的一种方法:
Textbox2.Text = string.Empty;
foreach(var c in Textbox1.Text)
{
Textbox2.Text += ((int)c).ToString();
}
VB.NET:
Textbox2.Text = String.Empty
For Each c As Char In Textbox1.Text
Textbox2.Text = Textbox2.Text + Convert.ToInt32(c).ToString()
Next
有:
Textbox2.Text
答案 2 :(得分:0)
TextBox2.Text = ""
For i As Integer = 0 To TextBox1.TextLength - 1
TextBox2.Text += Asc(TextBox1.Text(i)).ToString()
Next
答案 3 :(得分:0)
我修改了此Link
的代码Function AsciiEncode(ByVal value As String) As String
Dim encValue As New System.Text.StringBuilder(value.Length * 6)
Dim c As Char
For Each c In value
encValue.Append(Convert.ToInt32(c))
Next
Return encValue.ToString()
End Function
<强>用法:强>
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
TextBox2.Text = AsciiEncode(TextBox1.Text)
End Sub
答案 4 :(得分:0)
所有其他答案都适用于您给出的示例,但是,一些建议使用的是unicode编码而不是ASCII。如果严格遵守ASCII编码很重要,那么您应该明确指定要使用的编码。
Convert.ToInt32
使用UTF-16编码。我不确定CInt
会做什么,但我怀疑它的工作原理是一样的。使用Asc
更好,但它仍然依赖于线程的代码页设置,因此它仍然不是完全安全的。除此之外,Asc
是VB.NET中提供的旧VB6函数,主要用于向后兼容。
因此,我建议改用ASCIIEncoding
类。您可以使用ASCII
命名空间中Encoding
类的共享System.Text
属性来获取该类的实例,例如:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
builder.Append(b.ToString())
Next
Return builder.ToString()
End Function
然后,您可以像这样调用函数:
Textbox2.Text = ConvertTextToAsciiDigits(Textbox1.Text)
但是,我无法想象除非每个字符都产生两位数字,否则生成的字符串将可用。因此,我会通过这样的方式强制它为两位数:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException() ' Throws an exception if the value is three digits
End If
builder.Append(b.ToString("00")) ' Adds a leading zero to one-digit values
Next
Return builder.ToString()
End Function
如下面的评论中所述,要在每四位数后添加一个连字符,您可以跟踪自上一个连字符以来添加的总位数,如下所示:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
Dim digitsSinceHyphen As Integer = 0
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException()
End If
builder.Append(b.ToString("00"))
digitsSinceHyphen += 2
If digitsSinceHyphen >= 4 Then
builder.Append("-")
digitsSinceHyphen = 0
End If
Next
Return builder.ToString()
End Function