我已经从A-Z创建了一个字符串数组,其中包含0-25的索引。
然后我有一个文本框,当我在文本框中输入文本时,如何获得与我输入的文本相关联的数组的索引号?
例如,我在文本框中输入“AB”,索引返回值应为0和1.
如果我只输入一个字母的字母,下面的代码只能返回索引。如何返回许多字母的索引号?
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim abc(25) As String
abc(0) = "a"
abc(1) = "b"
abc(2) = "c"
abc(3) = "d"
abc(4) = "e"
abc(5) = "f"
abc(6) = "g"
abc(7) = "h"
abc(8) = "i"
abc(9) = "j"
abc(10) = "k"
abc(11) = "l"
abc(12) = "m"
abc(13) = "n"
abc(14) = "o"
abc(15) = "p"
abc(16) = "q"
abc(17) = "r"
abc(18) = "s"
abc(19) = "t"
abc(20) = "u"
abc(21) = "v"
abc(22) = "w"
abc(23) = "x"
abc(24) = "y"
abc(25) = "z"
Dim result = abc.Where(Function(a) a.Contains(TextBox2.Text)).Select(Function(s) Array.IndexOf(abc, s)).ToArray()
Dim x As Integer
For Each x In result
MsgBox(x)
Next
End Sub
答案 0 :(得分:1)
编译并完美运行:
Module Module1
Sub Main()
Test("Leniel")
End Sub
Sub Test(ByVal text As String)
Dim alphabet() As String = {"a", "b", "c", "d", "e",
"f", "g", "h", "i", "j",
"k", "l", "m", "n", "o",
"p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z"}
Dim indexes = From letter In text.ToCharArray() _
Select Array.IndexOf(alphabet, letter.ToString().ToLower())
Dim i As Integer
For Each i In indexes
MsgBox(i)
Next
End Sub
End Module
它将分别显示在消息框中:
'l e n i e l
11, 4, 13, 8, 4, 11
答案 1 :(得分:0)
首先想到的是在文本框输入上使用.split方法来获取字符数组。对数组中的每个元素执行搜索,将每个匹配添加到结果数组中。
答案 2 :(得分:0)
有一百万种方法可以解决这个问题。
一个解决方案:
1)获取文本
Dim theText = TextBox2.Text
2)对于该文本中的每个字母,获取该号码(并将其显示为消息
Dim c As Char
For Each c In theText
MsgBox(translateCharacter(c))
Next
Public Function translateCharacter(ByVal c As Char) As Integer
translateCharacter = abc.Where(Function(a) a.Contains(c)).Select(Function(s) Array.IndexOf(abc, s)).ToArray()
End Function
如果编译,它应该逐个弹出每个数字。我使用了与翻译角色相同的功能(即得到结果)。还有其他方法可以做到这一点,我只是想解决你的主要问题,指出你可以迭代字符串中的所有字符。
我希望有所帮助,
- gMale