0

i want to check if entered string is a Integer or not for example

12 = True

+12 = True

-5 = True

4.4 = False
4as = False

I make it using int.TryParse but what I want is to using ASCII without using int.TryParse

string str;
int strint;
int strintoA;
bool flag = false;

while (flag == false)
{
    Console.Write("Enter a Number : ");
    str = Console.ReadLine();
    flag = int.TryParse(str, out strint);              
    if (flag == false)
    {
        Console.WriteLine("Please Enter Numbers Only.");
    }
    else
    {
        strintoA = strint;
        Console.WriteLine("Entered String: " + str + " is a Number!" );
        break;
    }
}
Console.ReadKey();
JohnLBevan
  • 22,735
  • 13
  • 96
  • 178
Johnny
  • 1
  • 1
  • 5
    What's wrong with the int.TryParse aproach? – Klaus Gütter Nov 18 '18 at 16:43
  • 2
    If you absolutely can't use tryparse for whatever reason, you could use a regex as in this answer: https://stackoverflow.com/questions/9043551/regex-match-integer-only – Kevin Nov 18 '18 at 16:43
  • Not saying why you don't want to use `Int32.TryParse` makes this question too broad. (BTW—`String` and `Char` use UTF-16, not ASCII.) – Tom Blodget Nov 18 '18 at 18:20
  • If any provided answers have helped, etiquette is to mark this as "the answer" and probably upvote its usefulness. This prevents this question coming up under "show unanswered questions" in SOF and also gives some more reputation to the person who helped you. – Alex Leo Mar 02 '19 at 15:09

6 Answers6

2

You could also use regular expressions:

var regex = new Regex(@"^[-+]?\d+$");
var str = Console.ReadLine();
if (regex.IsMatch(str))
{
    Console.WriteLine($"{str} is a number!");
}
alxnull
  • 909
  • 9
  • 18
0

why dont use:

if(intString[0] == '+' || intString[0] == '-') intString = intString.Substring(1, intString.Length - 1);
bool isNumber = intString.All(char.IsDigit);
Mohsen
  • 4,049
  • 1
  • 31
  • 31
0

check the first char for -|+|digit, check rest isDigit

for (int i = 0; i < str.Length; i++)
{
    var c = str[i];
    if (i == 0)
    {
        if (!(c == '+' || c == '-' || char.IsDigit(c)) {
            return false;
        }
    }

    if (!char.IsDigit(c)) return false;
}
return true;
Isitar
  • 1,286
  • 12
  • 29
0

Not sure why you don't want to use int.TryParse but the following code should do:

static bool IsValidInteger(string s)
{
    var leadingSignSeen = false;
    var digitSeen = false;
    var toParse = s.Trim();

    foreach (var c in toParse)
    {
        if (c ==  ' ')
        {
            if (digitSeen)
                return false;
        }
        else if (c == '+' || c == '-')
        {
            if (leadingSignSeen || digitSeen)
                return false;

            leadingSignSeen = true;
        }
        else if (!char.IsDigit(c))
            return false;
        else
        {
            digitSeen = true;
        }
    }

    return true;
}

This will accept any integer with leading sign and leading and trailing spaces. Whitespaces between leading sign and digits are also accepted.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
InBetween
  • 32,319
  • 3
  • 50
  • 90
0

FYI: You can refactor your code to simplify it for exactly the same functional output:

void Main()
{
    int result;
    Console.Write("Enter a Number : ");
    while (!int.TryParse(Console.ReadLine(), out result))
    {
        Console.WriteLine("Please Enter Numbers Only.");
        Console.Write("Enter a Number : ");
    }
    Console.WriteLine($"Entered String: {result} is a Number!");
    Console.ReadKey();
}

If you have a good reason to not use int.TryParse (e.g. it's lacking some functionality, or this is an exercise where you've been asked to write your own) you could use the above replacing int.TryParse with a call to IsNumericCustom, assuming the below signature (or change type int to whatever data type you need to handle).

public bool IsNumericCustom(string input, out int output)
{
    //...
}

Or if you only care about whether the value's numeric and not the parsed value:

void Main()
{
    string result;
    Console.Write("Enter a Number : ");
    //while (!int.TryParse((result = Console.ReadLine()), out _))
    while (!IsNumericCustom((result = Console.ReadLine()))
    {
        Console.WriteLine("Please Enter Numbers Only.");
        Console.Write("Enter a Number : ");
    }
    Console.WriteLine($"Entered String: {result} is a Number!");
    Console.ReadKey();
}

public bool IsNumericCustom(string input)
{
    //...
}

As for the logic in the IsNumericCustom, it really depends on what you're hoping to achieve / why int.TryParse / decimal.TryParse etc aren't appropriate. Here's a couple of implementations (using different function names).

using System.Text.RegularExpressions; //https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netframework-4.7.2
//...
readonly Regex isNumeric = new Regex("^[+-]?\d*\.?\d*$", RegexOptions.Compiled); //treat "." as "0.0", ".9" as "0.9", etc
readonly Regex isInteger = new Regex("^[+-]?\d+$", RegexOptions.Compiled); //requires at least 1 digit; i.e. "" is not "0" 
readonly Regex isIntegerLike = new Regex("^[+-]?\d*\.?\0*$", RegexOptions.Compiled); //same as integer, only 12.0 is treated as 12, whilst 12.1 is invalid; i.e. only an integer if we can remove digits after the decimal point without truncating the value.

//...
public bool IsNumeric(string input)
{
    return isNumeric.IsMatch(input); //if you'd wanted 4.4 to be true, use this
}
public bool IsInteger(string input)
{
    return isInteger.IsMatch(input); //as you want 4.4 to be false, use this
}
public bool IsIntegerLike(string input)
{
    return isIntegerLike.IsMatch(input); //4.4 is false, but both 4 and 4.0 are true 
}
JohnLBevan
  • 22,735
  • 13
  • 96
  • 178
0

From your requirements it appears that you want to use ASCII code in order to assert whether the string entered is numeric or not.

This is the code I have come up with:

 string str;
    var index = 1;
    int strintoA = 0;
    bool isNegative = false;

    //ASCII list of numbers and signs
    List<int> allowedValues = new List<int> { 43, 45, 48, 49, 50, 51, 52, 53, 54, 55, 56, 
    57 };
    bool flag = false;

    while (!flag)
    {
        Console.WriteLine("Enter a Number : ");

        str = Console.ReadLine();

        if (str.Count(item => allowedValues.Contains((int)item)) == str.Count())
        {
            foreach (var item in str.Reverse())
            {               
                if (item != 43 && item != 45)
                {
                    strintoA += index * (item - 48);
                    index = index * 10;
                }
                else if(item == 45)
                {
                    isNegative = true;
                }
            }
            if(isNegative)
            {
                strintoA *= -1;
            }

            Console.WriteLine("Entered String: " + str + " is a Number!");
            flag = true;
        }
        else
        {
            Console.WriteLine("Please Enter Numbers Only.");
        }
    }
    Console.ReadKey();
}

The allowedValues list contains the ASCII representation of numeric values and allowed signs(+ and -). The foreach loop will regenerates the int value inserted.

Hope it helps.

Alex Leo
  • 2,781
  • 2
  • 13
  • 29
  • for better readability i suggest you use the actual representation ('+', '1', ...) instead of an integer number – Isitar Nov 18 '18 at 22:21