Convert VB code to C# which turns characters into numbers

Asked

Viewed 243 times

0

I have this code in VB and need to convert to C#.

Public Function eNumero(s As String) As Boolean
    If s = "" Then
        eNumero = False
    Else
        eNumero = Asc(s) >= Asc("0") And Asc(s) <= Asc("9")
    End If
End Function

I tried to convert, but it doesn’t work. The problem is in ASC function.

public bool eNumero(string s)
{
    if (s == "")
        eNumero = false;
    else
        eNumero = Strings.Asc(s) >= Strings.Asc("0") & Strings.Asc(s) <= Strings.Asc("9");
}
  • 1

    Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

3

The VB code is bad. It is not possible to properly convert an entire text to its ASCII numerical representation. It is possible to do this with a character. There are guarantees that the parameter string will always be a character? If it is, why doesn’t it come a type char? But come on:

public static bool eNumero(string s) {
    if (string.IsNullOrWhiteSpace(s)) return false;
    return (int)s[0] >= (int)'0' && (int)s[0] <= (int)'9';
}

I noticed other problems. The "if it is empty" check is wrong and may have problems depending on what comes. And you don’t need a variable, you can close the execution right there if it’s invalid. I made sure you only take the first character and make a cast in this character in a simple way. I used the operator && which is correct for this type of check. Using the cast literally is more efficient than doing a conversion.

using static System.Console;

public class Program {
    public static void Main() {
        WriteLine(eNumero(""));
        WriteLine(eNumero("a"));
        WriteLine(eNumero("5"));
    }
    public static bool eNumero(string s) {
        if (string.IsNullOrWhiteSpace(s)) return false;
        return (int)s[0] >= (int)'0' && (int)s[0] <= (int)'9';
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • if I just do (int)s[0] >= (int)'0', eNumero("a") will be positive. You can explain?

  • I have no idea what you’re talking about

  • Here: return (int)s[0] >= (int)'0';// && (int)s[0] <= (int)'9';

  • I still don’t know what you mean by that. If you have a new question on the subject, open a new one post, otherwise you need to say what you want.

  • @Júniormoreira it is not necessary to do (int)'3' when you can just put the 3.

  • @Cypherpotato this is wrong.

  • @Maniero conversion would not give the same meaning?

  • 1

    @Maniero now that I saw that it returns the Unicode code of the character, not the numerical conversion itself. It’s really wrong.

  • 1

    @Cypherpotato exactly what I realized, so the comments, as I am studying C# I found it pertinent to question to expand knowledge!

Show 4 more comments

3


Analyzing your code makes it easy to understand what function bool eNumero(string s) is a logical function that takes a string as input returns the logical value true indicating whether the first character of the input string is a number between 0 and 9, otherwise the function returns false. For this the function obtains the ASCII code of the first character of the input string, through the function of the Visual Basic native String.Asc(string), and then check if it is contained in the range of the ASCII table that comprises the numbers between 0 and 9.

I see two possible solutions. One is to continue using the Visual Basic function String.Asc(string) within a C# code or other solution would be to abandon the function bool eNumero(string s) for a ready-made and packaged solution within the . Net Framework.

To use native visual basic functions add the namespace Microsoft.VisualBasic to your project.

Go to and at Solution Explorer->Add Reference add the assemblies Microsoft.VisualBasic, Microsoft.VisualBasic.Compatibility and Microsoft.VisualBasic.Compatibility.Data.

In your code add the clause using Microsoft.VisualBasic;.

Note: in C# use operator return when you want to return a value.

using Microsoft.VisualBasic;

public class Program
{ 

    public static bool eNumero(string s)
    {    
        if (s == "") return false;
        else return Strings.Asc(s) >= Strings.Asc("0") && Strings.Asc(s) <= Strings.Asc("9");        
    }

    public static void Main()
    { 

        Console.WriteLine(eNumero("2365"));
    }
}

The other alternative is solution provided by the Framework, as I have already said, the abandonment of the eNumero and use or function Single.TryParse or depending on your needs just the Int32.TryParse. What I see advantage because the functions of the framework analyze in a single passage a string to check whether the input string is a number or not, while the function bool eNumero(string s) checks character by character and is not able to analyze more complex numerical structures.

The function Single.TryParse converts the string representation to a floating point number with equivalent simple precision by returning a logical value indicating whether the conversion was successful or not.

Already the function Int32.TryParse converts the string representation to a 32bit integer number by returning a logical value indicating whether the conversion was successful or not.

Examples of both use of Single.TryParse and of Int32.TryParse.

class Program
{
    static void Main(string[] args)
    {
       float f;
       int i;
       Console.WriteLine( (Single.TryParse("143.56", out f)) ? 
                                              (f + 102).ToString() : 
                                                   "não é um número"
                         );

       Console.WriteLine( (Single.TryParse("Teste", out f)) ? 
                                              (f + 102).ToString() : 
                                                   "não é um número"
                         );

       Console.WriteLine( (Int32.TryParse("2143", out i)) ?
                                          (i + 792).ToString() :
                                              "não é um número"
                         );
       // Nesse caso não trata-se de um zero e sim da letra O.
       Console.WriteLine( (Int32.TryParse("18O", out i)) ?
                                          (i + 792).ToString() :
                                              "não é um número"
                         );
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.