我需要创建一个函数,从a到z的字符串中计算每个字母的实例,并将其存储到整数数组中。我很擅长使用并行阵列,所以请耐心等待我。到目前为止,我有:
Function Letter(ByVal strTest As String) As Integer()
Const intMaxLetters As Integer = 25
Dim intLetters(intMaxLetters) As Integer
Dim value As String = "abcdefghijklmnopqrstuvwxyz"
Dim chrLetters() As Char = value.ToCharArray
Dim intCounter As Integer = 0
For intCounter = 0 To strTest.Length - 1
Dim c As Char = strTest.Substring(intCounter, 1)
If c >= chrLetters(0) And c <= chrLetters(25) Then
**intLetters()** += 1
End If
Next
Return intLetters
End Function
我必须在intLetters上传递什么参数才能为每个元素添加1?当然,intLetters(0)表示char a,而intLetters(25)表示z。谢谢! 另外,如果我要在多个控件中使用此数组(如表单上的两个按钮),那么我应该使用什么范围?谢谢!
答案 0 :(得分:2)
要回答您的具体问题,intLetters数组的索引是字符的ASCII值与&#34; a&#34;的ASCII值之间的差异。
我还会通过以下几种方式简化您的代码:
Char.IsLower
方法检查字符是否为小写字母,而不是创建包含所有小写字母的字符串。这是简化的功能。
Function Letter(strTest As String) As Integer()
Dim intLetters(25) As Integer
For Each c As Char In strTest 'use strTest.ToLower if you don't care about the case of the letter
If Char.IsLower(c) Then intLetters(Asc(c) - Asc("a"c)) += 1
Next
Return intLetters
End Function