Monthly Archives: November 2020
VB.NET || How To Validate An Email Address Using VB.NET
The following is a module with functions which demonstrates how to determine if an email address is valid using VB.NET.
This function is based on RFC2821 and RFC2822 to determine the validity of an email address.
1. Validate Email – Basic Usage
The example below demonstrates the use of ‘Utils.Email.IsValid‘ to determine if an email address is valid.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
' Validate Email Dim addresses = New List(Of String) From { "a@gmail.comm", "name@yah00.com", "_name@yah00.com", "name@again@example.com", "anystring@anystring.anystring", "prettyandsimple@example.com", "very.common@example.com", "disposable.style.email.with+symbol@example.com", "other.email-with-dash@example.com", "x@example.com", """much.more unusual""@example.com", """very.unusual.@.unusual.com""@example.com", "<< example-indeed@strange-example.com >>", "<< admin@mailserver1 >>", "<< #!$%&\'*+-/=?^_`{}|~@example.org >>", "example@s.solutions", "user@com", "john.doe@example..com", "john..doe@example.com", "A@b@c@example.com" } For Each email In addresses Debug.Print($"Email: {email}, Is Valid: {Utils.Email.IsValid(email)}") Next ' expected output: ' Email: a@gmail.comm, Is Valid: True ' Email: name@yah00.com, Is Valid: True ' Email: _name@yah00.com, Is Valid: False ' Email: name@again@example.com, Is Valid: False ' Email: anystring@anystring.anystring, Is Valid: True ' Email: prettyandsimple@example.com, Is Valid: True ' Email: very.common@example.com, Is Valid: True ' Email: disposable.style.email.with+symbol@example.com, Is Valid: True ' Email: other.email-with-dash@example.com, Is Valid: True ' Email: x@example.com, Is Valid: True ' Email: "much.more unusual"@example.com, Is Valid: False ' Email: "very.unusual.@.unusual.com"@example.com, Is Valid: False ' Email: << example-indeed@strange-example.com >>, Is Valid: False ' Email: << admin@mailserver1 >>, Is Valid: False ' Email: << #!$%&\'*+-/=?^_`{}|~@example.org >>, Is Valid: False ' Email: example@s.solutions, Is Valid: True ' Email: user@com, Is Valid: False ' Email: john.doe@example..com, Is Valid: False ' Email: john..doe@example.com, Is Valid: False ' Email: A@b@c@example.com, Is Valid: False |
2. Validate Email – Additional Options
The example below demonstrates the use of ‘Utils.Email.IsValid‘ to determine if an email address is valid with additional validation options.
Supplying options to verify an email address uses the default validity rules, in addition to the provided validation options.
This allows you to add custom rules to determine if an email is valid or not. For example, the misspelling of common email domains, or known spam domains.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
' Verify Email Using Default Rules With Additional Options Dim addresses = New List(Of String) From { "a@gmail.comm", "name@yah00.com", "prettyandsimple@bumpymail.com", "disposable@gold2world.com", "user@gold2world.biz" } ' Additional options Dim options = New Utils.Email.Options With { .InvalidDomains = { ' Optional: IEnumerable of invalid domains. Example: gmail.com "aichyna.com", "gawab.com", "gold2world.biz", "front14.org", "bumpymail.com", "pleasantphoto.com", "spam.la" }, .InvalidTopLevelDomains = New String() { ' Optional: IEnumerable of invalid top level domains. Example: .com "comm", "nett", "c0m" }, .InvalidSecondLevelDomains = New List(Of String) From { ' Optional: IEnumerable of invalid second level domains. Example: gmail "yah00", "ynail", "gnail" } } For Each email In addresses Debug.Print($"Email: {email}, Is Valid: {Utils.Email.IsValid(email, options)}") Next ' expected output: ' Email: a@gmail.comm, Is Valid: False ' Email: name@yah00.com, Is Valid: False ' Email: prettyandsimple@bumpymail.com, Is Valid: False ' Email: disposable@gold2world.com, Is Valid: True ' Email: user@gold2world.biz, Is Valid: False |
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 4, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils Public MustInherit Class Email ''' <summary> ''' Based on RFC2821 and RFC2822 to determine the validity of an ''' email address ''' </summary> ''' <param name="emailAddress">The email address to verify</param> ''' <param name="options">Additional email restrictions</param> ''' <returns>True if the email address is valid, false otherwise</returns> Public Shared Function IsValid(emailAddress As String, Optional options As Email.Options = Nothing) As Boolean If String.IsNullOrWhiteSpace(emailAddress) OrElse emailAddress.Length > 100 Then Return False End If Dim optionsPattern = If(options Is Nothing, String.Empty, options.Pattern) 'https://www.jochentopf.com/email/characters-in-email-addresses.pdf Dim pattern = "^[^a-zA-Z0-9]|[^a-zA-Z0-9]$" & ' First and last characters should be between a-z, A-Z, or 0-9. "|[\000-\052]|[\074-\077]" & ' Invalid characers between oct 000-052, and oct 074-077. "|^((?!@).)*$" & ' Must contain an '@' character. "|(@.*){2}" & ' Must not contain more than one '@' character. "|@[^.]*$" & ' Must contain at least one '.' character after the '@' character. "|~" & ' Invalid '~' character. "|\.@" & ' First character before the '@' must not be '.' character. "|@\." & ' First character after the '@' must not be '.' character. "|;|:|,|\^|\[|\]|\\|\{|\}|`|\t" & ' Must not contain various invalid characters. "|[\177-\377]" & ' Invalid characers between oct 177-377. "|\/|\.\.|^\.|\.$|@@" & ' Must not contain '/', '..', '@@' or end with '.' character. If(String.IsNullOrWhiteSpace(optionsPattern), String.Empty, $"|{optionsPattern}") Dim regex = New Text.RegularExpressions.Regex(pattern, Text.RegularExpressions.RegexOptions.IgnoreCase) Dim match = regex.Match(emailAddress) If match.Success Then 'Debug.Print("Email address '" & emailAddress & "' contains invalid char/string '" & match.Value & "'.") Return False End If Return True End Function Public Class Options Private Property data As New Dictionary(Of String, Object) Public Sub New() Dim properties = New String() { NameOf(InvalidDomains), NameOf(InvalidTopLevelDomains), NameOf(InvalidSecondLevelDomains), NameOf(Pattern) } For Each prop In properties data.Add(prop, Nothing) Next End Sub ''' <summary> ''' Invalid domains. Example: gmail.com ''' </summary> Public Property InvalidDomains As IEnumerable(Of String) Get Return GetData(Of IEnumerable(Of String))(NameOf(InvalidDomains)) End Get Set(value As IEnumerable(Of String)) SetData(NameOf(InvalidDomains), value) ResetPattern() End Set End Property ''' <summary> ''' Invalid top level domains. Example: .com ''' </summary> Public Property InvalidTopLevelDomains As IEnumerable(Of String) Get Return GetData(Of IEnumerable(Of String))(NameOf(InvalidTopLevelDomains)) End Get Set(value As IEnumerable(Of String)) SetData(NameOf(InvalidTopLevelDomains), value) ResetPattern() End Set End Property ''' <summary> ''' Invalid second level domains. Example: gmail ''' </summary> Public Property InvalidSecondLevelDomains As IEnumerable(Of String) Get Return GetData(Of IEnumerable(Of String))(NameOf(InvalidSecondLevelDomains)) End Get Set(value As IEnumerable(Of String)) SetData(NameOf(InvalidSecondLevelDomains), value) ResetPattern() End Set End Property Public ReadOnly Property Pattern As String Get If GetData(Of Object)(NameOf(Pattern)) Is Nothing Then Dim options = New List(Of String) If InvalidTopLevelDomains IsNot Nothing Then options.AddRange(InvalidTopLevelDomains.Select(Function(domain) FormatTld(domain))) End If If InvalidSecondLevelDomains IsNot Nothing Then options.AddRange(InvalidSecondLevelDomains.Select(Function(domain) FormatSld(domain))) End If If InvalidDomains IsNot Nothing Then options.AddRange(InvalidDomains.Select(Function(domain) FormatDomain(domain))) End If SetData(NameOf(Pattern), String.Join("|", options)) End If Return GetData(Of String)(NameOf(Pattern)) End Get End Property Private Function GetData(Of T)(key As String) As T Return CType(data(key), T) End Function Private Sub SetData(key As String, value As Object) data(key) = value End Sub Private Sub ResetPattern() SetData(NameOf(Pattern), Nothing) End Sub Private Function FormatTld(domain As String) As String If String.IsNullOrWhiteSpace(domain) Then Return domain End If Return AddPeriodSlash(AddPeriod(AddDollar(domain))) End Function Private Function FormatSld(domain As String) As String If String.IsNullOrWhiteSpace(domain) Then Return domain End If Return AddAt(domain) End Function Private Function FormatDomain(domain As String) As String If String.IsNullOrWhiteSpace(domain) Then Return domain End If Return AddPeriodSlash(AddAt(domain)) End Function Private Function AddDollar(domain As String) As String If Not domain.EndsWith("$") Then domain = $"{domain}$" End If Return domain End Function Private Function AddAt(domain As String) As String If Not domain.StartsWith("@") Then domain = $"@{domain}" End If Return domain End Function Private Function AddPeriod(domain As String) As String If Not domain.StartsWith(".") Then domain = $".{domain}" End If Return domain End Function Private Function AddPeriodSlash(domain As String) As String Dim index = domain.LastIndexOf(".") If index > -1 Then domain = domain.Insert(index, "\") End If Return domain End Function End Class End Class End Module End Namespace ' http://programmingnotes.org/ |
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 4, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Module Program Sub Main(args As String()) Try ' Verify email Dim addresses = New List(Of String) From { "a@gmail.comm", "name@yah00.com", "_name@yah00.com", "name@again@example.com", "anystring@anystring.anystring", "prettyandsimple@example.com", "very.common@example.com", "disposable.style.email.with+symbol@example.com", "other.email-with-dash@example.com", "x@example.com", """much.more unusual""@example.com", """very.unusual.@.unusual.com""@example.com", "<< example-indeed@strange-example.com >>", "<< admin@mailserver1 >>", "<< #!$%&\'*+-/=?^_`{}|~@example.org >>", "example@s.solutions", "user@com", "john.doe@example..com", "john..doe@example.com", "A@b@c@example.com" } For Each email In addresses Display($"Email: {email}, Is Valid: {Utils.Email.IsValid(email)}") Next Display("") ' Verify email using the default rules with additional options Dim addresses2 = New List(Of String) From { "a@gmail.comm", "name@yah00.com", "prettyandsimple@bumpymail.com", "disposable@gold2world.com", "user@gold2world.biz" } ' Additional options Dim options = New Utils.Email.Options With { .InvalidDomains = { ' IEnumerable of invalid domains. Example: gmail.com "aichyna.com", "gawab.com", "gold2world.biz", "front14.org", "bumpymail.com", "pleasantphoto.com", "spam.la" }, .InvalidTopLevelDomains = New String() { ' IEnumerable of invalid top level domains. Example: .com "comm", "nett", "c0m" }, .InvalidSecondLevelDomains = New List(Of String) From { ' IEnumerable of invalid second level domains. Example: gmail "yah00", "ynail" } } For Each email In addresses2 Display($"Email: {email}, Is Valid: {Utils.Email.IsValid(email, options)}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Validate A Phone Number Using VB.NET
The following is a module with functions which demonstrates how to validate a phone number using VB.NET.
Not only does this function check formatting, but follows NANP numbering rules by ensuring that the first digit in the area code and the first digit in the second section are 2-9.
1. Validate Phone Number
The example below demonstrates the use of ‘Utils.IsValidPhoneNumber‘ to determine if a phone number is valid.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
' Validate Phone Number Dim numbers = New List(Of String) From { "(123) 456-7890", "(123)456-7890", "123-456-7890", "123.456.7890", "1234567890", "+31636363634", "075-63546725", "(657) 278-2011", "(657)278-2011", "(657)2782011", "6572782011", "+6572782011", "657-278-2011", "657 278 2011", "657.278.2011", "1657.278.2011", "+6572782011", "16572782011", "657-2782011" } For Each number In numbers Debug.Print($"Number: {number}, Is Valid: {Utils.IsValidPhoneNumber(number)}") Next ' expected output: ' Number: (123) 456-7890, Is Valid: False ' Number: (123)456-7890, Is Valid: False ' Number: 123-456-7890, Is Valid: False ' Number: 123.456.7890, Is Valid: False ' Number: 1234567890, Is Valid: False ' Number: +31636363634, Is Valid: False ' Number: 075-63546725, Is Valid: False ' Number: (657) 278-2011, Is Valid: True ' Number: (657)278-2011, Is Valid: True ' Number: (657)2782011, Is Valid: True ' Number: 6572782011, Is Valid: True ' Number: +6572782011, Is Valid: True ' Number: 657-278-2011, Is Valid: True ' Number: 657 278 2011, Is Valid: True ' Number: 657.278.2011, Is Valid: True ' Number: 1657.278.2011, Is Valid: True ' Number: +6572782011, Is Valid: True ' Number: 16572782011, Is Valid: True ' Number: 657-2782011, Is Valid: True |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 3, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Not only checks formatting, but follows NANP numbering rules ''' by ensuring that the first digit in the area code and the first ''' digit in the second section are 2-9. ''' </summary> ''' <param name="phoneNumber">The phone number to verify</param> ''' <returns>True if the phone number is valid, false otherwise</returns> Public Function IsValidPhoneNumber(phoneNumber As String) As Boolean If String.IsNullOrWhiteSpace(phoneNumber) Then Return False End If Dim pattern = "^[\+]?[{1}]?[(]?[2-9]\d{2}[)]?[-\s\.]?[2-9]\d{2}[-\s\.]?[0-9]{4}$" Static regex As New Text.RegularExpressions.Regex(pattern, Text.RegularExpressions.RegexOptions.Compiled Or Text.RegularExpressions.RegexOptions.IgnoreCase) Return regex.IsMatch(phoneNumber) End Function End Module End Namespace ' http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 3, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Module Program Sub Main(args As String()) Try Dim numbers = New List(Of String) From { "(123) 456-7890", "(123)456-7890", "123-456-7890", "123.456.7890", "1234567890", "+31636363634", "075-63546725", "(657) 278-2011", "(657)278-2011", "(657)2782011", "6572782011", "+6572782011", "657-278-2011", "657 278 2011", "657.278.2011", "1657.278.2011", "+6572782011", "16572782011", "657-2782011" } For Each number In numbers Display($"Number: {number}, Is Valid: {Utils.IsValidPhoneNumber(number)}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Shuffle & Randomize An Array/List/IEnumerable Using VB.NET
The following is a module with functions which demonstrates how to randomize and shuffle the contents of an Array/List/IEnumerable using VB.NET.
This function shuffles an IEnumerable and returns the results as a new List(Of T).
This function is generic, so it should work on IEnumerables of any datatype.
1. Shuffle – Integer Array
The example below demonstrates the use of ‘Utils.Shuffle‘ to randomize an integer array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
' Shuffle - Integer Array Imports Utils Dim numbers = New Integer() {1987, 19, 22, 2009, 2019, 1991, 28, 31} Dim results = numbers.Shuffle For Each item In results Debug.Print($"{item}") Next ' example output: ' 2009 ' 1987 ' 31 ' 22 ' 28 ' 2019 ' 1991 ' 19 |
2. Shuffle – String List
The example below demonstrates the use of ‘Utils.Shuffle‘ to randomize a list of strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
' Shuffle - String List Imports Utils Dim names = New List(Of String) From { "Kenneth", "Jennifer", "Lynn", "Sole" } Dim results = names.Shuffle For Each item In results Debug.Print($"{item}") Next ' example output: ' Sole ' Kenneth ' Lynn ' Jennifer |
3. Shuffle – Custom Object List
The example below demonstrates the use of ‘Utils.Shuffle‘ to randomize a list of custom objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
' Shuffle - Custom Object List Imports Utils Public Class Part Public Property PartName As String Public Property PartId As Integer End Class Dim parts = New List(Of Part) From { New Part With { .PartName = "crank arm", .PartId = 1234 }, New Part With { .PartName = "chain ring", .PartId = 1334 }, New Part With { .PartName = "regular seat", .PartId = 1434 }, New Part With { .PartName = "banana seat", .PartId = 1444 }, New Part With { .PartName = "cassette", .PartId = 1534 }, New Part With { .PartName = "shift lever", .PartId = 1634 }} Dim results = parts.Shuffle For Each item In results Debug.Print($"{item.PartId} {item.PartName}") Next ' example output: ' 1634 shift lever ' 1444 banana seat ' 1434 regular seat ' 1234 crank arm ' 1334 chain ring ' 1534 cassette |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 3, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Shuffles an IEnumerable and returns the results as a List ''' </summary> ''' <param name="list">The IEnumerable list to shuffle</param> ''' <returns>A List of shuffled items from the IEnumerable</returns> <Runtime.CompilerServices.Extension()> Function Shuffle(Of T)(list As IEnumerable(Of T)) As List(Of T) Dim r = New Random Dim shuffled = list.ToList For index = 0 To shuffled.Count - 1 Dim randomIndex = r.Next(index, shuffled.Count) If index <> randomIndex Then Dim temp = shuffled(index) shuffled(index) = shuffled(randomIndex) shuffled(randomIndex) = temp End If Next Return shuffled End Function End Module End Namespace ' http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 3, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Imports Utils Module Program Public Class Part Public Property PartName As String Public Property PartId As Integer End Class Sub Main(args As String()) Try Dim numbers = New Integer() {1987, 19, 22, 2009, 2019, 1991, 28, 31} Dim results = numbers.Shuffle For Each item In results Display($"{item}") Next Display("") Dim names = New List(Of String) From { "Kenneth", "Jennifer", "Lynn", "Sole" } Dim results1 = names.Shuffle For Each item In results1 Display($"{item}") Next Display("") Dim parts = New List(Of Part) From { New Part With { .PartName = "crank arm", .PartId = 1234 }, New Part With { .PartName = "chain ring", .PartId = 1334 }, New Part With { .PartName = "regular seat", .PartId = 1434 }, New Part With { .PartName = "banana seat", .PartId = 1444 }, New Part With { .PartName = "cassette", .PartId = 1534 }, New Part With { .PartName = "shift lever", .PartId = 1634 }} Dim results2 = parts.Shuffle For Each item In results2 Display($"{item.PartId} {item.PartName}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || Word Wrap – How To Split A String Text Into lines With Maximum Length
The following is a module with functions which demonstrates how to split text into multiple lines using VB.NET.
The following function is an extension method, which takes a string, and splits it into multiple lines (array indices) of a specified length.
An optional boolean parameter specifies whether this function should break up long individual words to fit as many characters as possible on a line.
With this option enabled, if a word is too long to fit on a line, the word is broken up to fit as many characters as possible up to the maximum length on the current line, and the remaining characters gets moved to the next line (the next array index).
Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!
1. Word Wrap – Don’t Break Words
The example below demonstrates the use of ‘Utils.WordWrap‘ to split a string into multiple lines.
In this example, individual words are not broken up. They are simply moved onto the next line (if necessary).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
' Word Wrap - Don't Break Words Imports Utils ' Limit string text to 40 characters per line Dim text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus faucibus venenatis justo, placerat maximus tortor dictum non. Curabitur efficitur pulvinar arcu, id vehicula nisi commodo in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vivamus consectetur ut orci scelerisque fringilla. Sed id nisl ac nunc congue suscipit at sollicitudin elit. Nullam tempus tortor sit amet molestie rutrum. Sed a sollicitudin magna, eget vulputate tortor. Proin ut sodales orci, a iaculis ipsum.Ut nec odio risus. Vivamus viverra metus turpis. Pellentesque lacinia lacinia tempus. Suspendisse in justo eget orci porttitor ornare vitae nec tortor. Donec dolor odio, dapibus non sodales quis, volutpat a turpis. Curabitur eget fermentum ante. Donec pulvinar nulla non ante mattis aliquam.Aenean vulputate, ligula sit amet laoreet porttitor, magna justo pellentesque diam, id tempus eros orci ut arcu. Praesent et finibus ipsum. Mauris luctus, metus vel sagittis pharetra, felis odio placerat felis, et ullamcorper neque turpis eget tellus. Maecenas vel imperdiet augue. Morbi imperdiet diam ac enim cursus venenatis. Donec eros turpis, pharetra a aliquet sed, vehicula sed libero. Donec efficitur volutpat ex, in euismod dolor tristique at. Quisque a nisi ultricies libero lacinia fringilla nec vel tortor.Aenean id felis et quam lacinia ornare. Curabitur blandit, arcu eget ultricies pulvinar, neque lectus ultrices mauris, vitae feugiat mauris diam id tellus. Vestibulum finibus cursus dui et feugiat. Sed vitae sagittis lorem. Duis suscipit sollicitudin est tempor efficitur. Morbi eget fringilla massa. Integer ullamcorper, ligula congue consequat sodales, dolor eros pretium augue, in luctus enim massa quis est. Fusce cursus ac ipsum quis aliquet. Curabitur pharetra lectus non suscipit scelerisque. Pellentesque vitae scelerisque tellus. Donec sit amet ligula felis. Donec ac hendrerit magna, sed pharetra diam. Morbi gravida felis finibus sodales suscipit. In hac habitasse platea dictumst.Curabitur purus erat, tincidunt vel tincidunt et, fermentum eget dui. Fusce eu justo vel massa ultrices lacinia sit amet quis augue. Nunc fringilla justo quis felis fringilla, at rutrum justo venenatis. Ut ullamcorper gravida finibus. Donec fermentum varius metus sit amet porttitor. Sed at auctor velit. Quisque et urna metus. Donec ut mi vel turpis dignissim pulvinar. Curabitur massa leo, interdum ac urna id, dictum pellentesque nunc. Ut dolor justo, vehicula quis porta in, laoreet eget augue. this is a test pneumonoultramicroscopicsilicovolcanoconiosis" Dim maxCharacters = 40 Dim result = text.WordWrap(maxCharacters) For Each line In result Display($"Length: {line.Length} - {line}") Next ' expected output: ' Length: 39 - Lorem ipsum dolor sit amet, consectetur ' Length: 35 - adipiscing elit. Phasellus faucibus ' Length: 40 - venenatis justo, placerat maximus tortor ' Length: 40 - dictum non. Curabitur efficitur pulvinar ' Length: 34 - arcu, id vehicula nisi commodo in. ' Length: 35 - Interdum et malesuada fames ac ante ' Length: 33 - ipsum primis in faucibus. Vivamus ' Length: 31 - consectetur ut orci scelerisque ' Length: 37 - fringilla. Sed id nisl ac nunc congue ' Length: 37 - suscipit at sollicitudin elit. Nullam ' Length: 39 - tempus tortor sit amet molestie rutrum. ' Length: 40 - Sed a sollicitudin magna, eget vulputate ' Length: 40 - tortor. Proin ut sodales orci, a iaculis ' Length: 40 - ipsum.Ut nec odio risus. Vivamus viverra ' Length: 34 - metus turpis. Pellentesque lacinia ' Length: 36 - lacinia tempus. Suspendisse in justo ' Length: 36 - eget orci porttitor ornare vitae nec ' Length: 37 - tortor. Donec dolor odio, dapibus non ' Length: 32 - sodales quis, volutpat a turpis. ' Length: 36 - Curabitur eget fermentum ante. Donec ' Length: 30 - pulvinar nulla non ante mattis ' Length: 36 - aliquam.Aenean vulputate, ligula sit ' Length: 35 - amet laoreet porttitor, magna justo ' Length: 38 - pellentesque diam, id tempus eros orci ' Length: 35 - ut arcu. Praesent et finibus ipsum. ' Length: 33 - Mauris luctus, metus vel sagittis ' Length: 39 - pharetra, felis odio placerat felis, et ' Length: 37 - ullamcorper neque turpis eget tellus. ' Length: 35 - Maecenas vel imperdiet augue. Morbi ' Length: 40 - imperdiet diam ac enim cursus venenatis. ' Length: 37 - Donec eros turpis, pharetra a aliquet ' Length: 31 - sed, vehicula sed libero. Donec ' Length: 39 - efficitur volutpat ex, in euismod dolor ' Length: 38 - tristique at. Quisque a nisi ultricies ' Length: 32 - libero lacinia fringilla nec vel ' Length: 38 - tortor.Aenean id felis et quam lacinia ' Length: 36 - ornare. Curabitur blandit, arcu eget ' Length: 32 - ultricies pulvinar, neque lectus ' Length: 37 - ultrices mauris, vitae feugiat mauris ' Length: 34 - diam id tellus. Vestibulum finibus ' Length: 32 - cursus dui et feugiat. Sed vitae ' Length: 29 - sagittis lorem. Duis suscipit ' Length: 40 - sollicitudin est tempor efficitur. Morbi ' Length: 29 - eget fringilla massa. Integer ' Length: 36 - ullamcorper, ligula congue consequat ' Length: 37 - sodales, dolor eros pretium augue, in ' Length: 40 - luctus enim massa quis est. Fusce cursus ' Length: 32 - ac ipsum quis aliquet. Curabitur ' Length: 28 - pharetra lectus non suscipit ' Length: 31 - scelerisque. Pellentesque vitae ' Length: 34 - scelerisque tellus. Donec sit amet ' Length: 39 - ligula felis. Donec ac hendrerit magna, ' Length: 38 - sed pharetra diam. Morbi gravida felis ' Length: 32 - finibus sodales suscipit. In hac ' Length: 35 - habitasse platea dictumst.Curabitur ' Length: 39 - purus erat, tincidunt vel tincidunt et, ' Length: 38 - fermentum eget dui. Fusce eu justo vel ' Length: 36 - massa ultrices lacinia sit amet quis ' Length: 38 - augue. Nunc fringilla justo quis felis ' Length: 40 - fringilla, at rutrum justo venenatis. Ut ' Length: 34 - ullamcorper gravida finibus. Donec ' Length: 31 - fermentum varius metus sit amet ' Length: 39 - porttitor. Sed at auctor velit. Quisque ' Length: 37 - et urna metus. Donec ut mi vel turpis ' Length: 40 - dignissim pulvinar. Curabitur massa leo, ' Length: 40 - interdum ac urna id, dictum pellentesque ' Length: 35 - nunc. Ut dolor justo, vehicula quis ' Length: 39 - porta in, laoreet eget augue. this is a ' Length: 4 - test ' Length: 45 - pneumonoultramicroscopicsilicovolcanoconiosis |
2. Word Wrap – Break Words
The example below demonstrates the use of ‘Utils.WordWrap‘ to split a string into multiple lines.
In this example, individual words are broken up and moved onto the next line (if necessary), with the default hyphen character used, which is a dash (‘-‘).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
' Word Wrap - Break Words Imports Utils ' Limit string text to 40 characters per line Dim text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus faucibus venenatis justo, placerat maximus tortor dictum non. Curabitur efficitur pulvinar arcu, id vehicula nisi commodo in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vivamus consectetur ut orci scelerisque fringilla. Sed id nisl ac nunc congue suscipit at sollicitudin elit. Nullam tempus tortor sit amet molestie rutrum. Sed a sollicitudin magna, eget vulputate tortor. Proin ut sodales orci, a iaculis ipsum.Ut nec odio risus. Vivamus viverra metus turpis. Pellentesque lacinia lacinia tempus. Suspendisse in justo eget orci porttitor ornare vitae nec tortor. Donec dolor odio, dapibus non sodales quis, volutpat a turpis. Curabitur eget fermentum ante. Donec pulvinar nulla non ante mattis aliquam.Aenean vulputate, ligula sit amet laoreet porttitor, magna justo pellentesque diam, id tempus eros orci ut arcu. Praesent et finibus ipsum. Mauris luctus, metus vel sagittis pharetra, felis odio placerat felis, et ullamcorper neque turpis eget tellus. Maecenas vel imperdiet augue. Morbi imperdiet diam ac enim cursus venenatis. Donec eros turpis, pharetra a aliquet sed, vehicula sed libero. Donec efficitur volutpat ex, in euismod dolor tristique at. Quisque a nisi ultricies libero lacinia fringilla nec vel tortor.Aenean id felis et quam lacinia ornare. Curabitur blandit, arcu eget ultricies pulvinar, neque lectus ultrices mauris, vitae feugiat mauris diam id tellus. Vestibulum finibus cursus dui et feugiat. Sed vitae sagittis lorem. Duis suscipit sollicitudin est tempor efficitur. Morbi eget fringilla massa. Integer ullamcorper, ligula congue consequat sodales, dolor eros pretium augue, in luctus enim massa quis est. Fusce cursus ac ipsum quis aliquet. Curabitur pharetra lectus non suscipit scelerisque. Pellentesque vitae scelerisque tellus. Donec sit amet ligula felis. Donec ac hendrerit magna, sed pharetra diam. Morbi gravida felis finibus sodales suscipit. In hac habitasse platea dictumst.Curabitur purus erat, tincidunt vel tincidunt et, fermentum eget dui. Fusce eu justo vel massa ultrices lacinia sit amet quis augue. Nunc fringilla justo quis felis fringilla, at rutrum justo venenatis. Ut ullamcorper gravida finibus. Donec fermentum varius metus sit amet porttitor. Sed at auctor velit. Quisque et urna metus. Donec ut mi vel turpis dignissim pulvinar. Curabitur massa leo, interdum ac urna id, dictum pellentesque nunc. Ut dolor justo, vehicula quis porta in, laoreet eget augue. this is a test pneumonoultramicroscopicsilicovolcanoconiosis" Dim maxCharacters = 40 Dim result = text.WordWrap(maxCharacters, True) For Each line In result Display($"Length: {line.Length} - {line}") Next ' expected output: ' Length: 39 - Lorem ipsum dolor sit amet, consectetur ' Length: 40 - adipiscing elit. Phasellus faucibus ven- ' Length: 40 - enatis justo, placerat maximus tortor d- ' Length: 39 - ictum non. Curabitur efficitur pulvinar ' Length: 40 - arcu, id vehicula nisi commodo in. Inte- ' Length: 40 - rdum et malesuada fames ac ante ipsum p- ' Length: 38 - rimis in faucibus. Vivamus consectetur ' Length: 40 - ut orci scelerisque fringilla. Sed id n- ' Length: 40 - isl ac nunc congue suscipit at sollicit- ' Length: 40 - udin elit. Nullam tempus tortor sit amet ' Length: 40 - molestie rutrum. Sed a sollicitudin mag- ' Length: 40 - na, eget vulputate tortor. Proin ut sod- ' Length: 38 - ales orci, a iaculis ipsum.Ut nec odio ' Length: 40 - risus. Vivamus viverra metus turpis. Pe- ' Length: 40 - llentesque lacinia lacinia tempus. Susp- ' Length: 40 - endisse in justo eget orci porttitor or- ' Length: 40 - nare vitae nec tortor. Donec dolor odio, ' Length: 40 - dapibus non sodales quis, volutpat a tu- ' Length: 40 - rpis. Curabitur eget fermentum ante. Do- ' Length: 40 - nec pulvinar nulla non ante mattis aliq- ' Length: 40 - uam.Aenean vulputate, ligula sit amet l- ' Length: 40 - aoreet porttitor, magna justo pellentes- ' Length: 38 - que diam, id tempus eros orci ut arcu. ' Length: 40 - Praesent et finibus ipsum. Mauris luctu- ' Length: 40 - s, metus vel sagittis pharetra, felis o- ' Length: 40 - dio placerat felis, et ullamcorper neque ' Length: 40 - turpis eget tellus. Maecenas vel imperd- ' Length: 39 - iet augue. Morbi imperdiet diam ac enim ' Length: 40 - cursus venenatis. Donec eros turpis, ph- ' Length: 40 - aretra a aliquet sed, vehicula sed libe- ' Length: 40 - ro. Donec efficitur volutpat ex, in eui- ' Length: 39 - smod dolor tristique at. Quisque a nisi ' Length: 38 - ultricies libero lacinia fringilla nec ' Length: 40 - vel tortor.Aenean id felis et quam laci- ' Length: 40 - nia ornare. Curabitur blandit, arcu eget ' Length: 40 - ultricies pulvinar, neque lectus ultric- ' Length: 39 - es mauris, vitae feugiat mauris diam id ' Length: 40 - tellus. Vestibulum finibus cursus dui et ' Length: 39 - feugiat. Sed vitae sagittis lorem. Duis ' Length: 40 - suscipit sollicitudin est tempor effici- ' Length: 40 - tur. Morbi eget fringilla massa. Integer ' Length: 40 - ullamcorper, ligula congue consequat so- ' Length: 40 - dales, dolor eros pretium augue, in luc- ' Length: 40 - tus enim massa quis est. Fusce cursus ac ' Length: 38 - ipsum quis aliquet. Curabitur pharetra ' Length: 40 - lectus non suscipit scelerisque. Pellen- ' Length: 38 - tesque vitae scelerisque tellus. Donec ' Length: 40 - sit amet ligula felis. Donec ac hendrer- ' Length: 40 - it magna, sed pharetra diam. Morbi grav- ' Length: 38 - ida felis finibus sodales suscipit. In ' Length: 39 - hac habitasse platea dictumst.Curabitur ' Length: 39 - purus erat, tincidunt vel tincidunt et, ' Length: 38 - fermentum eget dui. Fusce eu justo vel ' Length: 40 - massa ultrices lacinia sit amet quis au- ' Length: 40 - gue. Nunc fringilla justo quis felis fr- ' Length: 38 - ingilla, at rutrum justo venenatis. Ut ' Length: 40 - ullamcorper gravida finibus. Donec ferm- ' Length: 38 - entum varius metus sit amet porttitor. ' Length: 40 - Sed at auctor velit. Quisque et urna me- ' Length: 40 - tus. Donec ut mi vel turpis dignissim p- ' Length: 38 - ulvinar. Curabitur massa leo, interdum ' Length: 40 - ac urna id, dictum pellentesque nunc. Ut ' Length: 40 - dolor justo, vehicula quis porta in, la- ' Length: 40 - oreet eget augue. this is a test pneumo- ' Length: 39 - noultramicroscopicsilicovolcanoconiosis |
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 3, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Takes in a string and splits it into multiple lines (array indices) ''' of a specified length. If a word is too long to fit on a line, ''' the word gets moved to the next line (the next array index) ''' </summary> ''' <param name="text">The text to word wrap</param> ''' <param name="maxCharactersPerLine">The maximum characters per ''' line</param> ''' <param name="breakWords">Determine if words should fit as many as ''' possible on current line, with remaining broken up to the next line</param> ''' <param name="hyphenChar">The character to use at the end of the line ''' as a hyphen when breaking up words</param> ''' <param name="hyphenatedWordMinLength">The minimum length of the ''' hyphenated word after it is broken up. A word will not be hyphenated ''' unless it meets this minimum length after it is broken up</param> ''' <returns>A list of strings that contains each line limited by ''' the specified length</returns> <Runtime.CompilerServices.Extension()> Public Function WordWrap(text As String, maxCharactersPerLine As Integer, Optional breakWords As Boolean = False, Optional hyphenChar As Char? = "-"c, Optional hyphenatedWordMinLength As Integer = 1) As List(Of String) If breakWords AndAlso hyphenatedWordMinLength >= maxCharactersPerLine Then Throw New System.InvalidOperationException($"Unable to fit the value of '{NameOf(hyphenatedWordMinLength)}' ({hyphenatedWordMinLength}) with '{NameOf(maxCharactersPerLine)}' ({maxCharactersPerLine}). Either increase the value of '{NameOf(maxCharactersPerLine)}' or decrease the value of '{NameOf(hyphenatedWordMinLength)}'") End If text = text.Trim() Dim result = New List(Of String)() If text.Length <= maxCharactersPerLine Then result.Add(text) Else Dim words = text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries) Dim leftOver = String.Empty Dim wordIndex As Integer = 0 While wordIndex < words.Length OrElse Not String.IsNullOrWhiteSpace(leftOver) Dim currentResultLineIndex = result.Count - 1 Dim currentResultLineLength = If(currentResultLineIndex > -1, result(currentResultLineIndex).Length, 0) ' Start string with left over text from previous word Dim addition = String.Empty If Not String.IsNullOrWhiteSpace(leftOver) Then If currentResultLineLength > 0 _ AndAlso currentResultLineLength < maxCharactersPerLine _ AndAlso Not leftOver.StartsWith(" ") Then addition &= " " End If addition &= leftOver End If ' Add current word to string If wordIndex < words.Length Then Dim word = words(wordIndex).Trim() If currentResultLineLength > 0 AndAlso Not addition.EndsWith(" ") Then addition &= " " End If addition &= word End If If breakWords Then ' Determine how many characters to take from the current addition Dim remainingLineLength = maxCharactersPerLine - currentResultLineLength Dim charactersToAddLength = Math.Min((If(remainingLineLength > 0, remainingLineLength, maxCharactersPerLine)), addition.Length) ' Include hyphen if word will be broken up If charactersToAddLength > 1 AndAlso charactersToAddLength < addition.Length Then Dim slice = addition.Substring(0, charactersToAddLength) If Not String.IsNullOrWhiteSpace(slice) Then If Not hyphenChar.HasValue OrElse Not slice(charactersToAddLength - 1) = hyphenChar Then ' Determine the length of the hyphenated word Dim hyphenatedWordLength = 0 Dim hyphenInsertIndexStart = charactersToAddLength - 1 While hyphenInsertIndexStart >= 0 _ AndAlso Not Char.IsWhiteSpace(slice(hyphenInsertIndexStart)) hyphenatedWordLength += 1 hyphenInsertIndexStart -= 1 End While ' Subtract the hypenated character from the result If hyphenChar.HasValue Then hyphenatedWordLength -= 1 End If If hyphenatedWordLength >= hyphenatedWordMinLength Then addition = addition.Insert(charactersToAddLength - 1, If(hyphenChar.HasValue, hyphenChar.ToString(), String.Empty)) ElseIf hyphenInsertIndexStart >= 0 AndAlso (Not hyphenChar.HasValue OrElse Not addition(hyphenInsertIndexStart) = hyphenChar) Then addition = addition.Insert(hyphenInsertIndexStart, New String(" "c, hyphenatedWordMinLength)) End If End If End If End If currentResultLineLength += charactersToAddLength ' Save excess characters from current addition for the next line leftOver = If(charactersToAddLength < addition.Length, addition.Substring(charactersToAddLength), String.Empty) ' Only take the specified characters from the string addition = addition.Substring(0, charactersToAddLength) Else currentResultLineLength += addition.Length End If ' Add or append words to result If result.Count < 1 OrElse currentResultLineLength > maxCharactersPerLine Then ' Start new line addition = addition.Trim() result.Add(addition) Else ' Append existing line result(currentResultLineIndex) &= addition End If wordIndex += 1 End While End If ' Remove excess whitespace For index = 0 To result.Count - 1 result(index) = result(index).Trim() Next Return result End Function End Module End Namespace ' http://programmingnotes.org/ |
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 3, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Imports Utils Public Module Program Sub Main(args As String()) Try ' Limit string text to 40 characters per line Dim text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus faucibus venenatis justo, placerat maximus tortor dictum non. Curabitur efficitur pulvinar arcu, id vehicula nisi commodo in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vivamus consectetur ut orci scelerisque fringilla. Sed id nisl ac nunc congue suscipit at sollicitudin elit. Nullam tempus tortor sit amet molestie rutrum. Sed a sollicitudin magna, eget vulputate tortor. Proin ut sodales orci, a iaculis ipsum.Ut nec odio risus. Vivamus viverra metus turpis. Pellentesque lacinia lacinia tempus. Suspendisse in justo eget orci porttitor ornare vitae nec tortor. Donec dolor odio, dapibus non sodales quis, volutpat a turpis. Curabitur eget fermentum ante. Donec pulvinar nulla non ante mattis aliquam.Aenean vulputate, ligula sit amet laoreet porttitor, magna justo pellentesque diam, id tempus eros orci ut arcu. Praesent et finibus ipsum. Mauris luctus, metus vel sagittis pharetra, felis odio placerat felis, et ullamcorper neque turpis eget tellus. Maecenas vel imperdiet augue. Morbi imperdiet diam ac enim cursus venenatis. Donec eros turpis, pharetra a aliquet sed, vehicula sed libero. Donec efficitur volutpat ex, in euismod dolor tristique at. Quisque a nisi ultricies libero lacinia fringilla nec vel tortor.Aenean id felis et quam lacinia ornare. Curabitur blandit, arcu eget ultricies pulvinar, neque lectus ultrices mauris, vitae feugiat mauris diam id tellus. Vestibulum finibus cursus dui et feugiat. Sed vitae sagittis lorem. Duis suscipit sollicitudin est tempor efficitur. Morbi eget fringilla massa. Integer ullamcorper, ligula congue consequat sodales, dolor eros pretium augue, in luctus enim massa quis est. Fusce cursus ac ipsum quis aliquet. Curabitur pharetra lectus non suscipit scelerisque. Pellentesque vitae scelerisque tellus. Donec sit amet ligula felis. Donec ac hendrerit magna, sed pharetra diam. Morbi gravida felis finibus sodales suscipit. In hac habitasse platea dictumst.Curabitur purus erat, tincidunt vel tincidunt et, fermentum eget dui. Fusce eu justo vel massa ultrices lacinia sit amet quis augue. Nunc fringilla justo quis felis fringilla, at rutrum justo venenatis. Ut ullamcorper gravida finibus. Donec fermentum varius metus sit amet porttitor. Sed at auctor velit. Quisque et urna metus. Donec ut mi vel turpis dignissim pulvinar. Curabitur massa leo, interdum ac urna id, dictum pellentesque nunc. Ut dolor justo, vehicula quis porta in, laoreet eget augue. this is a test pneumonoultramicroscopicsilicovolcanoconiosis" Dim maxCharacters = 40 Dim result = text.WordWrap(maxCharacters) For Each line In result Display($"Length: {line.Length} - {line}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Get First/Last Day Of The Week And The First/Last Day Of The Month
The following is a module with functions which demonstrates how to get the first and last day of the week, as well as how to get the first and last day of the month using VB.NET.
1. First & Last Day Of Week
The example below demonstrates the use of ‘Utils.DateRange.GetWeekStartAndEnd‘ to get the first and last day of the week.
By default, the start of the week is set on Monday. This can be changed by setting the second parameter to any valid property contained in the Microsoft.VisualBasic.FirstDayOfWeek enum.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
' First & Last Day Of Week Dim weekResult = Utils.DateRange.GetWeekStartAndEnd(Date.Today) Debug.Print($" Today = {Date.Today.ToShortDateString} Week Start = {weekResult.StartDate.ToShortDateString} Week End = {weekResult.EndDate.ToShortDateString} ") ' expected output: ' Today = 11/2/2020 ' Week Start = 11/2/2020 ' Week End = 11/8/2020 |
2. First & Last Day Of Month
The example below demonstrates the use of ‘Utils.DateRange.GetMonthStartAndEnd‘ to get the first and last day of the week.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
' First & Last Day Of Month Dim monthResult = Utils.DateRange.GetMonthStartAndEnd(Date.Today) Debug.Print($" Today = {Date.Today.ToShortDateString} Month Start = {monthResult.StartDate.ToShortDateString} Month End = {monthResult.EndDate.ToShortDateString} ") ' expected output: ' Today = 11/2/2020 ' Month Start = 11/1/2020 ' Month End = 11/30/2020 |
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 2, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils Public Class DateRange Public Property StartDate As Date Public Property EndDate As Date ''' <summary> ''' Takes in a date and returns the first and last day of the week ''' </summary> ''' <param name="date">The reference date in question</param> ''' <param name="firstDayOfWeek">The day the week starts on</param> ''' <returns>An object that contains the date range result</returns> Public Shared Function GetWeekStartAndEnd([date] As Date, Optional firstDayOfWeek As Microsoft.VisualBasic.FirstDayOfWeek = Microsoft.VisualBasic.FirstDayOfWeek.Monday) As DateRange Dim result = New DateRange result.StartDate = [date].AddDays(1 - Weekday([date], firstDayOfWeek)).Date result.EndDate = result.StartDate.AddDays(6).Date Return result End Function ''' <summary> ''' Takes in a date and returns the first and last day of the month ''' </summary> ''' <param name="date">The reference date in question</param> ''' <returns>An object that contains the date range result</returns> Public Shared Function GetMonthStartAndEnd([date] As Date) As DateRange Dim result = New DateRange result.StartDate = New Date([date].Year, [date].Month, 1).Date result.EndDate = result.StartDate.AddMonths(1).AddDays(-1).Date Return result End Function End Class End Module End Namespace ' http://programmingnotes.org/ |
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 2, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Module Program Sub Main(args As String()) Try Dim weekResult = Utils.DateRange.GetWeekStartAndEnd(Date.Today) Display($" Today = {Date.Today.ToShortDateString} Week Start = {weekResult.StartDate.ToShortDateString} Week End = {weekResult.EndDate.ToShortDateString} ") Dim monthResult = Utils.DateRange.GetMonthStartAndEnd(Date.Today) Display($" Today = {Date.Today.ToShortDateString} Month Start = {monthResult.StartDate.ToShortDateString} Month End = {monthResult.EndDate.ToShortDateString} ") Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || Roman Numeral Conversion – How To Convert Roman Numeral To Integer & Integer To Roman Numeral
The following is a program with functions which demonstrates how to convert roman numerals to integer, and integers to roman numerals.
The sample program implemented on this page was presented in a Data Structures course. This program was assigned in order to practice the use of the class data structure.
1. Roman Numeral Conversion
The example below demonstrates how to convert integers to roman numerals and roman numerals to integers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 2, 2020 ' Taken From: http://programmingnotes.org/ ' File: romanNumeralConversion.vb ' Description: The following demonstrates how to convert roman numerals. ' ============================================================================ Option Strict On Option Explicit On Imports System Module Program Sub Main(args As String()) Try Dim decimalNumber = 1987 DecimalTest(decimalNumber) Display("") Dim roman = "MCMXCI" RomanTest(roman) Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub RomanTest(roman As String) Dim decimalNumber = RomanNumeral.ConvertToDecimal(roman) Dim convertedBack = RomanNumeral.ConvertToRoman(decimalNumber) Display("======= Roman Test Start =======") Display($"Original = {roman} Converted = {decimalNumber} Converted Back To Original = {convertedBack}") Display("======= Roman Test End =======") End Sub Public Sub DecimalTest(decimalNumber As Decimal) Dim roman = RomanNumeral.ConvertToRoman(decimalNumber) Dim convertedBack = RomanNumeral.ConvertToDecimal(roman) Display("======= Decimal Test Start =======") Display($"Original = {decimalNumber} Converted = {roman} Converted Back To Original = {convertedBack}") Display("======= Decimal Test End =======") End Sub ''' <summary> ''' Class to hold Roman Numeral Conversion Values ''' </summary> Public Class RomanNumeral Public Property [decimal] As Decimal Public Property roman As String ''' <summary> ''' Converts a Decimal number to a Roman Numeral ''' </summary> ''' <param name="decimal">Decimal number to be converted</param> Public Shared Function ConvertToRoman(decimalNumber As Decimal) As String Dim stbRoman = New Text.StringBuilder If decimalNumber > 0 Then Dim conversionValues = GetValues() For Each conversionValue In conversionValues While decimalNumber > 0 _ AndAlso decimalNumber >= conversionValue.decimal stbRoman.Append(conversionValue.roman) decimalNumber -= conversionValue.decimal End While If decimalNumber <= 0 Then Exit For End If Next End If Dim roman = stbRoman.ToString Return roman End Function ''' <summary> ''' Converts a Roman Numeral to a Decimal value ''' </summary> ''' <param name="roman">Roman Numeral value to be converted</param> Public Shared Function ConvertToDecimal(roman As String) As Decimal Dim decimalNumber As Decimal = 0 If Not String.IsNullOrWhiteSpace(roman) Then Dim previousNumber As Decimal = 0 Dim conversionValues = GetValues() ' Iterate the string starting from the end For index = roman.Length - 1 To 0 Step -1 Dim currentLetter = roman(index).ToString ' Skip whitepsace characters If String.IsNullOrWhiteSpace(currentLetter) Then Continue For End If ' Find a conversion value that matches the current letter Dim conversionValue = (From x In conversionValues Where x.roman.ToLower = currentLetter.ToLower Select x Take 1).FirstOrDefault ' If a valid conversion was found, get the value If conversionValue Is Nothing Then Continue For End If Dim currentNumber = conversionValue.decimal ' Calculate the result If previousNumber > currentNumber Then decimalNumber -= currentNumber Else decimalNumber += currentNumber End If ' Save the current number in order to process the next letter previousNumber = currentNumber Next End If Return decimalNumber End Function ''' <summary> ''' Returns Roman Numeral Conversion Values ''' </summary> Public Shared Function GetValues() As List(Of RomanNumeral) Dim conversionValues = New List(Of RomanNumeral) From { New RomanNumeral With {.decimal = 1000, .roman = "M"}, New RomanNumeral With {.decimal = 900, .roman = "CM"}, New RomanNumeral With {.decimal = 500, .roman = "D"}, New RomanNumeral With {.decimal = 400, .roman = "CD"}, New RomanNumeral With {.decimal = 100, .roman = "C"}, New RomanNumeral With {.decimal = 90, .roman = "XC"}, New RomanNumeral With {.decimal = 50, .roman = "L"}, New RomanNumeral With {.decimal = 40, .roman = "XL"}, New RomanNumeral With {.decimal = 10, .roman = "X"}, New RomanNumeral With {.decimal = 9, .roman = "IX"}, New RomanNumeral With {.decimal = 5, .roman = "V"}, New RomanNumeral With {.decimal = 4, .roman = "IV"}, New RomanNumeral With {.decimal = 1, .roman = "I"} } Return conversionValues.OrderByDescending(Function(x) x.decimal).ToList() End Function End Class Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
======= Decimal Test Start =======
Original = 1987
Converted = MCMLXXXVII
Converted Back To Original = 1987
======= Decimal Test End ============== Roman Test Start =======
Original = MCMXCI
Converted = 1991
Converted Back To Original = MCMXCI
======= Roman Test End =======
C++ || Roman Numeral Conversion – How To Convert Roman Numeral To Integer & Integer To Roman Numeral Using C++
The following is a program with functions which demonstrates how to convert roman numerals to integer, and integers to roman numerals.
The sample program implemented on this page is an updated version of a homework assignment which was presented in a C++ Data Structures course. This program was assigned in order to practice the use of the class data structure, which is very similar to the struct data structure.
1. Roman Numeral Conversion
The example below demonstrates how to convert integers to roman numerals and roman numerals to integers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
// ============================================================================ // Author: Kenneth Perkins // Taken From: http://programmingnotes.org/ // Date: Nov 2, 2020 // File: romanNumeralConversion.cpp // Description: The following demonstrates how to convert roman numerals. // ============================================================================ #include <iostream> #include <vector> #include <string> #include <cctype> #include <algorithm> /** * USE: Converts values from decimal to roman numeral and back */ class RomanNumeral { private: double m_decimal; std::string m_roman; bool m_isEmpty; public: RomanNumeral() { this->m_isEmpty = true; } RomanNumeral(double decimal, std::string roman) { this->m_decimal = decimal; this->m_roman = roman; this->m_isEmpty = false; } double decimal() const { return this->m_decimal; } std::string roman() const { return this->m_roman; } bool isEmpty() const { return this->m_isEmpty; } /** * FUNCTION: convertToRoman * USE: Converts a decimal number to a roman numeral * @param decimal: The number to be converted to a roman numeral. * @return: The converted roman numeral value. */ static std::string convertToRoman(double decimal) { std::string roman = ""; if (decimal > 0) { auto conversionValues = getValues(); for (const auto& conversionValue : conversionValues) { while (decimal > 0 && decimal >= conversionValue.decimal()) { roman += conversionValue.roman(); decimal -= conversionValue.decimal(); } if (decimal <= 0) { break; } } } return roman; } /** * FUNCTION: convertToDecimal * USE: Converts a roman numeral to a decimal value * @param roman: The number to be converted to a decimal number. * @return: The converted decimal value. */ static double convertToDecimal(std::string roman) { double decimal = 0; if (!isEmpty(roman)) { double previousNumber = 0; auto conversionValues = getValues(); // Iterate the std::string starting from the end for (int index = roman.length() - 1; index >= 0; --index) { // Get the current letter std::string currentLetter = std::string(1, roman[index]); // Skip whitepsace characters if (isEmpty(currentLetter)) { continue; } // Find a conversion value that matches the current letter auto conversionValue = find(conversionValues, currentLetter); // If a valid conversion was found, get the value if (conversionValue.isEmpty()) { continue; } auto currentNumber = conversionValue.decimal(); // Calculate the result if (previousNumber > currentNumber) { decimal -= currentNumber; } else { decimal += currentNumber; } // Save the current number in order to process the next letter previousNumber = currentNumber; } } return decimal; } // Returns roman Numeral Conversion Values static std::vector<RomanNumeral> getValues() { std::vector<RomanNumeral> conversionValues; conversionValues.push_back(RomanNumeral(1000, "M")); conversionValues.push_back(RomanNumeral(900, "CM")); conversionValues.push_back(RomanNumeral(500, "D")); conversionValues.push_back(RomanNumeral(400, "CD")); conversionValues.push_back(RomanNumeral(100, "C")); conversionValues.push_back(RomanNumeral(90, "XC")); conversionValues.push_back(RomanNumeral(50, "L")); conversionValues.push_back(RomanNumeral(40, "XL")); conversionValues.push_back(RomanNumeral(10, "X")); conversionValues.push_back(RomanNumeral(9, "IX")); conversionValues.push_back(RomanNumeral(5, "V")); conversionValues.push_back(RomanNumeral(4, "IV")); conversionValues.push_back(RomanNumeral(1, "I")); // Sort the list in descending roman numeral order std::sort(conversionValues.begin(), conversionValues.end(), [](const auto& lhs, const auto& rhs) { return lhs.decimal() > rhs.decimal(); }); return conversionValues; } // Finds a conversion that matches the given roman numeral search value static RomanNumeral find(std::vector<RomanNumeral> conversionValues, std::string searchValue) { RomanNumeral result; searchValue = toLower(searchValue); auto predicate = [searchValue](auto x) { return (toLower(x.roman()) == searchValue); }; auto iter = std::find_if(conversionValues.begin(), conversionValues.end(), predicate); if (iter != conversionValues.end()) { result = *iter; } return result; } // Checks if a string is empty or only contains whitespace static bool isEmpty(std::string str) { return str.empty() || std::all_of(str.begin(), str.end(), [](char c) { return std::isspace(static_cast<unsigned char>(c)); }); } // Converts a string to lowercase static std::string toLower(std::string str) { std::transform(str.begin(), str.end(), str.begin(), [](char c) { return std::tolower(static_cast<unsigned char>(c)); }); return str; } }; void display(std::string message) { message += "\n"; std::cout << message; } void romanTest(std::string roman) { auto decimal = RomanNumeral::convertToDecimal(roman); auto convertedBack = RomanNumeral::convertToRoman(decimal); display("======= Roman Test Start ======="); display("Original = " + roman + "\n Converted = " + std::to_string(decimal) + "\n Converted Back To Original = " + convertedBack); display("======= Roman Test End ======="); } void decimalTest(double decimal) { auto roman = RomanNumeral::convertToRoman(decimal); auto convertedBack = RomanNumeral::convertToDecimal(roman); display("======= Decimal Test Start ======="); display("Original = " + std::to_string(decimal) + "\n Converted = " + roman + "\n Converted Back To Original = " + std::to_string(convertedBack)); display("======= Decimal Test End ======="); } int main() { auto decimal = 1987; decimalTest(decimal); display(""); auto roman = "McMxcI"; romanTest(roman); std::cin.get(); return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
======= Decimal Test Start =======
Original = 1987.000000
Converted = MCMLXXXVII
Converted Back To Original = 1987.000000
======= Decimal Test End ============== Roman Test Start =======
Original = McMxcI
Converted = 1991.000000
Converted Back To Original = MCMXCI
======= Roman Test End =======
C++ || Telephone Digit Program – How To Convert Letters To Numbers Using C++
The following is a program with functions which demonstrates how to implement a telephone digit program which converts the letters on a phone number keypad to digits.
The program allows to convert more than one letter at a time, include a hyphen, and allows both upper and lower case.
For example, the input text of “get loan”, the output would be:
438-5626
1. Telephone Digit Program
The example below demonstrates how to convert letters to numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
// ============================================================================ // Author: Kenneth Perkins // Date: Nov 1, 2020 // Taken From: http://programmingnotes.org/ // File: telephone.cpp // Description: Converts letters to digits in a telephone number // ============================================================================ #include <iostream> #include <string> #include <map> #include <cctype> #include <exception> #include <stdexcept> #include <algorithm> std::string convertNumber(std::string phoneNumber) { // Remove whitespace from string phoneNumber.erase(std::remove_if(phoneNumber.begin(), phoneNumber.end(), [](char c) { return std::isspace(static_cast<unsigned char>(c)); }), phoneNumber.end()); // Check if string is valid if (phoneNumber.length() < 1 || phoneNumber.length() > 10) { throw std::invalid_argument {phoneNumber + " is not a valid phone number"}; } const std::string keypad = "22233344455566677778889999"; std::map<char, char> alphabet; // Build the phone number mapping alphabet for (unsigned index = 0; index < keypad.length(); ++index) { alphabet['a' + index] = alphabet['A' + index] = keypad[index]; } // Convert the letters to numbers std::string result = ""; for (const auto& ch : phoneNumber) { auto number = ch; if (!std::isdigit(number)) { auto search = alphabet.find(number); if (search == alphabet.end()) { // Invalid input continue; } number = search->second; } result += number; } // Add the hyphens if necessary if (result.length() > 9) { result.insert(result.length() - 4, "-"); } if (result.length() > 3) { result.insert(3, "-"); } return result; } int main() { std::cout << "This is a program to convert letters to" << " their corresponding telephone digits." << std::endl << std::endl << "Enter your letters: "; std::string phoneNumber = ""; std::getline(std::cin, phoneNumber); try { std::cout << "\nThe number converted: " << convertNumber(phoneNumber) << std::endl; } catch (std::exception& e) { std::cout << "\nAn error occurred: " << e.what(); } std::cin.get(); return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Note: the code was compiled separate times to display different output)
====== RUN 1 ======
This is a program to convert letters to their corresponding telephone digits.
Enter your letters: get loan
The number converted: 438-5626
====== RUN 2 ======
This is a program to convert letters to their corresponding telephone digits.
Enter your letters: getloan
The number converted: 438-5626
====== RUN 3 ======
This is a program to convert letters to their corresponding telephone digits.
Enter your letters: get-loan
The number converted: 438-5626
====== RUN 4 ======
This is a program to convert letters to their corresponding telephone digits.
Enter your letters: GETLOAN
The number converted: 438-5626
====== RUN 5 ======
This is a program to convert letters to their corresponding telephone digits.
Enter your letters: G e T L O a N
The number converted: 438-5626
====== RUN 6 ======
This is a program to convert letters to their corresponding telephone digits.
Enter your letters: 6572782011
The number converted: 657-278-2011