Search code examples
vb.netif-statement

Convert A-H to ABCDEFGH VB.Net


I am developing a program, in which the end user enters a string (A-B, A-C, A-D... A-Z), this string would be converted for example...

If it is A-C, the string would be converted to ABC and in turn generate three text files with certain information (FileA, FileB and FileC) and so on for the other strings.

If stringC = "A-C" then
    stringC = "ABC"
elseif stringC = "A-D" then
    stringC = "ABCD"
...
elseif stringC = "A-Z" then
    stringC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
End If

I was thinking of developing it by using conditionals (if ... then ... elseif ... End If) that identify each string, but I would be left with a very extensive tree of conditionals if it went up to A-Z. Any ideas to simplify it?

Regards, thank you in advance.


Solution

  • you can use substring, if you pass in something like "D-X" use split then get the index of D and the index of X.

    here is the fiddle. https://dotnetfiddle.net/Ag0S81

      Dim alphabet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
          
            Dim GetAlphabetRange As Func(Of String, String) = Function(query As String) _
                alphabet.Substring(
                    alphabet.IndexOf(Char.Parse(query.Split("-"c)(0))),
                    alphabet.IndexOf(Char.Parse(query.Split("-"c)(1))) - 
                    alphabet.IndexOf(Char.Parse(query.Split("-"c)(0))) + 1)
    
            ' Test the function with different ranges
            Console.WriteLine(GetAlphabetRange("A-N"))
            Console.WriteLine(GetAlphabetRange("C-F"))
            Console.WriteLine(GetAlphabetRange("X-Z"))