3

I have created a string array from A-Z, which will contain indexes from 0-25.

Then I have a textbox and when I enter text into the textbox, how can I get the index number of the array associated with the text I entered?

For example, I enter "AB" into the textbox, and the index return should be 0 and 1.

The code below is only able to return the index if I enter only one letter alphabet. How do I return the index number for many alphabets?

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

4 Answers 4

1

Compiled and running perfectly:

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

It will show in the message box respectively:

'l   e  n   i  e  l
 11, 4, 13, 8, 4, 11
Sign up to request clarification or add additional context in comments.

Comments

1

I will "attack" that problem using a dictionary rather than an array. Each letter of the alphabet is a key with value corresponding to an index.

I don't think is a good idea creating the alphabet every time a call is made. Define the alphabet only once and use it as much as needed.

Module Module1

    'Byte datatype is suffice for this example.
    Dim Alphabet As Dictionary(Of String, Byte)

    Sub Main()

        Alphabet = New Dictionary(Of String, Byte)

        'Dim letters(25) As String
        'letters(0) = "a" : letters(1) = "b" : letters(2) = "c"
        'letters(3) = "d" : letters(4) = "e" : letters(5) = "f"
        'letters(6) = "g" : letters(7) = "h" : letters(8) = "i"
        'letters(9) = "j" : letters(10) = "k" : letters(11) = "l"
        'letters(12) = "m" : letters(13) = "n" : letters(14) = "o"
        'letters(15) = "p" : letters(16) = "q" : letters(17) = "r"
        'letters(18) = "s" : letters(19) = "t" : letters(20) = "u"
        'letters(21) = "v" : letters(22) = "w" : letters(23) = "x"
        'letters(24) = "y" : letters(25) = "z"
        'GenerateAlphabet(letters)

        'Or define alphabet like this
        Dim letters 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 æ ø å"
        GenerateAlphabet(letters)

        'Generating a couple of ways to test
        Dim words1 As New List(Of String) From {
            "Hello",
            "World",
            "I",
            "somehow",
            "exist"
        }
        Dim sentence As String = "Hello World I somehow exist"
        'Dim words2 As String() = {"Hello", "World", ""}'This will throw exception on the last word
        'Dim oneWord As String() = {"ThisIsOneWord!"} 'This will throw exception on the last char

        Try
            Testing(words1)
            Testing(sentence)
            'Testing(words2)
            'Testing(oneWord)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try

        Console.ReadKey()
    End Sub

    Private Sub GenerateAlphabet(alphabet_chars As ICollection(Of String))
        Populate(alphabet_chars)
    End Sub

    Private Sub GenerateAlphabet(alphabet_chars As String)
        Populate(alphabet_chars.Split({" "c}, StringSplitOptions.RemoveEmptyEntries))
    End Sub

    Public Sub Testing(words As ICollection(Of String))
        If words IsNot Nothing AndAlso words.Count <> 0 Then
            For i = 0 To words.Count - 1
                Console.WriteLine(String.Join(" ", GetIndices(words(i).ToLower())))
            Next
        Else
            Throw New ArgumentException($"'{NameOf(words)}' cannot be null or empty.", NameOf(words))
        End If
    End Sub

    Public Sub Testing(sentence As String)
        If sentence IsNot Nothing AndAlso sentence <> String.Empty AndAlso sentence.Length <> 0 Then
            Dim words = sentence.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
            For i = 0 To words.Count - 1
                Console.WriteLine(String.Join(" ", GetIndices(words(i).ToLower())))
            Next
        Else
            Throw New ArgumentException($"'{NameOf(sentence)}' cannot be null or empty.", NameOf(sentence))
        End If
    End Sub

    Private Sub Populate(letters As ICollection(Of String))
        Dim indx As Byte
        For Each letter In letters
            Alphabet.Add(letter.ToLower(), indx)
            'remove cast if indx is of type int32 and (indx +=1 can be used.)
            indx = CByte(indx + 1)
        Next
    End Sub

    Private Function GetIndices(word As String) As IEnumerable(Of Byte)

        If String.IsNullOrEmpty(word) OrElse String.IsNullOrWhiteSpace(word) Then
            Throw New ArgumentException($"'{NameOf(word)}' cannot be null, empty or whitespace.", NameOf(word))
        End If

        Dim retValue(word.Length - 1) As Byte
        Dim currChar As Char 'current char

        For i = 0 To word.Length - 1
            currChar = word(i)
            If Alphabet.ContainsKey(currChar) Then
                retValue(i) = Alphabet(word(i))
            Else
                Throw New Exception($"An invalid char was found. [{currChar}] is not part of the defined alphabet.")
            End If
        Next

        Return retValue
    End Function

End Module

7 Comments

Please elaborate on your answer
What more elaborated you need? Once the dictionary contains the letters and respective indices, the process is trivial, i.e. loop the chars in the input string in any matter you want and retrieve the index of each char from the dictionary.
You are suggesting an alternative way for the searching. Currently the answer does not address the problem OP is actually facing. Also, it adds no useful information to existing answers which were posted about 10 years ago. The answer strikes me as effortless and unclear without further elaboration. You could edit your answer to provide more details.
The use of dictionary simply enables another method of searching. This is not addressing the problem described.
I am not suggesting an alternative search. I am suggesting the usage of another data structure (dictionary) to address the problem described. If you cannot see the difference about the usage of a dictionary instead of the array structure and how to get the answer, Good luck on your coding ;). I think someone reading my answer will get it right away. .Not sure why you are mention the time of last answer, if that is a real issue!
|
0

There are a million ways to approach this.

One solution:

1) Get the text

Dim theText = TextBox2.Text

2) For each letter in that text, get the number (and display it as a message

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

Provided that compiles, it should pop up each number, one by one. I used the same function you were using to translate the character (i.e. get the result). There are other ways to do this, I just wanted to address your main question by point out that you can iterate over all the characters in the string.

I hope that helps,

--gMale

Comments

0

The first thing that comes to mind is to use the .split method on the textbox input to get an array of characters. Perform your search on each element in the array, adding each match to the result array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.