switch a string to an integer

  • Thread starter Thread starter El Camino
  • Start date Start date
E

El Camino

I need to switch a string to an integer

if its strLetter = "A"
integer value of 1

if its strLetter = "B" then
integer value of 2

if its strLetter = "C" then
integer value of 3

if its strLetter = "D" then
integer value of 4

wihtout goiing threw and extensive selection process....
Maybe a function that im not aware of....
and so on...
Thanx
 
Got it if anybody is interested..

AscW(strLetter - 64)

will convert to its appropriate number
 
Try this funtion:
Public Funtion LetterValue(c as char) as integer
if Asc(c) >96 then
return Asc(c) - 96
else
return Asc(c)- 64
end if
End Function

HTH

Jim Mirra
 
How about...

Public Function GetNum(ByVal c As Char) As Integer
Return Asc(c.ToUpper(c)) - 64
End Function

This handles both upper and lowercase

Regards,

Martin.
 
Martin,
I would recommend two changes:
Public Function GetNum(ByVal c As Char) As Integer
Return AscW(Char.ToUpper(c)) - 64
End Function

Seeing as Char.ToUpper is a shared method, its more obvious in your code if
you give the Class name (Char) when you call it as oppose to the variable.
Although you can use a Char variable to call the method, it appears that you
are acting on that instance of the variable, when you are not, you are
acting on the parameter...

Also using AscW function will not attempt to translate the char in relation
to the current code page.

Otherwise I think your sample is the "most flexible".

Hope this helps
Jay
 
* "El Camino said:
I need to switch a string to an integer

if its strLetter = "A"
integer value of 1

if its strLetter = "B" then
integer value of 2

if its strLetter = "C" then
integer value of 3

if its strLetter = "D" then
integer value of 4

\\\
Dim s As String = "A"
Dim i As Integer = Asc(s) - 64
///
 
Hi Martin,

Nice one, to make it more generic I would add

\\\
Public Function GetNum(ByVal c As Char) As Integer
If AscW(Char.ToUpper(c)) - 64 > 0 AndAlso AscW(Char.ToUpper(c)) - 64 < 27
Then
Return AscW(Char.ToUpper(c)) - 64
Else
Return 0
End if
End Function
///

Just my thought.

Cor
 
Back
Top