Reputation: 1
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();
Upvotes: 0
Views: 1524
Reputation: 2851
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.
Upvotes: 0
Reputation: 24430
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
}
Upvotes: 0
Reputation: 32750
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.
Upvotes: 0
Reputation: 4235
why dont use:
if(intString[0] == '+' || intString[0] == '-') intString = intString.Substring(1, intString.Length - 1);
bool isNumber = intString.All(char.IsDigit);
Upvotes: 0
Reputation: 919
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!");
}
Upvotes: 2
Reputation: 1449
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;
Upvotes: 0