Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to get all letter combinations of a phone number given a string of digits from 2-9 in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

' Letter Combinations of a Phone Number
' Given a string containing digits from 2-9, 
' get all possible letter combinations that a phone number represents

Class Program
    Private letters As List(Of String) = New List(Of String) From {
        "abc",
        "def",
        "ghi",
        "jkl",
        "mno",
        "pqrs",
        "tuv",
        "wxyz"
    }
    Private result As List(Of String) = New List(Of String)()

    Private Sub Print(ByVal lst As List(Of String))
        For Each n As String In lst
            Console.Write(n & " ")
        Next

        Console.WriteLine()
    End Sub

    Private Sub CreateCombinations(ByVal digits As String, ByVal output As String, ByVal di As Integer)
        If digits.Length = di Then
            result.Add(output)
            Return
        End If

        ' Use Convert.ToByte to get the ASCII value of the character and calculate the index
        Dim index As Integer = Convert.ToByte(digits(di)) - Convert.ToByte("2"c)
        For i As Integer = 0 To letters(index).Length - 1
            output += letters(index)(i)
            CreateCombinations(digits, output, di + 1)
            output = output.Substring(0, output.Length - 1)
        Next
    End Sub

    Private Function LetterCombinationsOfPhoneNumber(ByVal digits As String) As List(Of String)
        If digits = "" Then
            Return result
        End If

        Dim output As String = ""
        CreateCombinations(digits, output, 0)
        Return result
    End Function

	Public Shared Sub Main(ByVal args As String())
        Dim p As Program = New Program()
        Dim result As List(Of String) = p.LetterCombinationsOfPhoneNumber("23")
        p.Print(result)
    End Sub
End Class


' run:
'
' ad ae af bd be bf cd ce cf 
' 
 

 



answered Apr 25, 2025 by avibootz
...