使用基于数组索引的数组数据替换字符串

时间:2010-07-14 00:49:18

标签: vb.net

我有一个包含a-z的数组。 然后我有一个文本框,当单击该按钮时,它将文本框内的文本替换为数组的索引号。 例如,从“abc”将变为“0 1 2” 下面的代码完成了这项工作。 我可以知道如何这样做,我可以根据数组将文本框中的文本从“0 1 2”替换回“abc”吗?谢谢

Dim txtKey As String = readKeyTxt.Text
    readKeyTxt.Text = ""

    For Each b As String In txtKey
        If chars.Contains(b) Then
            Dim ab As Integer = Array.IndexOf(chars, b)
            b = Replace(LCase(b), b, ab & " ")

            readKeyTxt.Text &= b
        End If
    Next

2 个答案:

答案 0 :(得分:0)

以下是一些示例代码,可以执行您所描述的操作。但我有这种奇怪的感觉,这是家庭作业。

Imports System
Imports System.Text

Module Module1

   Sub Main()
      ' I don't really care how you get your chars... but if they aren't all there they
      ' will be lost in the conversion...
      Dim lstChars As New List(Of Char)
      For i As Integer = AscW("A"c) To AscW("z")
         lstChars.Add(ChrW(i))
      Next
      lstChars.Add(" "c)
      lstChars.Add("."c)
      Dim chars() As Char = lstChars.ToArray()

      Dim testString As String = "The Quick Brown Fox Jumped Over The Lazy Dog."
      Dim converted1 As String = ConvertStringToIndexes(testString, chars)
      Dim converted2 As String = ConvertIndexesToString(converted1, chars)

      Console.WriteLine(testString)
      Console.WriteLine(converted1)
      Console.WriteLine(converted2)

      Console.ReadKey(True)
   End Sub

   Private Function ConvertStringToIndexes(ByVal s As String, ByVal chars() As Char) As String
      Dim result As New StringBuilder()
      Dim firstPass As Boolean = True
      For Each c As Char In s.ToCharArray()
         Dim idx = Array.IndexOf(chars, c)
         If idx >= 0 Then
            If firstPass Then
               firstPass = False
            Else
               result.Append(" ")
            End If
            result.Append(idx)
         End If
      Next
      Return result.ToString()
   End Function

   Private Function ConvertIndexesToString(ByVal s As String, ByVal chars() As Char) As String
      Dim indexes() As String = s.Split(" "c)
      Dim result As New StringBuilder()

      For Each item As String In indexes
         Dim idx As Integer = 0
         If Int32.TryParse(item, idx) AndAlso chars.Length > idx Then
            result.Append(chars(idx))
         End If
      Next
      Return result.ToString()
   End Function

End Module

答案 1 :(得分:0)

感谢您的帮助。是的,这是一个功课,我设法用其他方法解决它。这是代码。

 Dim charList As New List(Of String)

    For Each line In IO.File.ReadAllLines(Form1.broFreTxt.Text, System.Text.Encoding.Default)
        charList.Add(line(1))
    Next

    Dim chars = charList.ToArray()
    Dim rslt As New List(Of String)
    Dim data1() As String = outSubtracTxt.Text.Split(" ")

    For Each b As String In data1

        b = Replace(LCase(b), b, chars(b) & " ")
        rslt.Add(b)

    Next

    Dim numbersAsString() As String = Array.ConvertAll(rslt.ToArray, New Converter(Of String, String)(Function(i) i.ToString))