Skip to content

Instantly share code, notes, and snippets.

@atsvetkov
Last active December 25, 2016 19:26
Show Gist options
  • Save atsvetkov/f0e8f82a9590ceda0edc0b157f11b68d to your computer and use it in GitHub Desktop.
Save atsvetkov/f0e8f82a9590ceda0edc0b157f11b68d to your computer and use it in GitHub Desktop.
using System;
class Program
{
static void Main(string[] args)
{
foreach (var number in new object[] { 123, "2017", "-1", "1a2b3c", '5' })
{
try
{
int result;
if (IntegerParser.TryParse(number, out result))
{
Console.WriteLine($"Parsed {number.GetType()} {number}, got {result}");
}
else
{
Console.WriteLine($"Could not parse {number.GetType()} {number}");
}
}
catch (Exception e)
{
Console.WriteLine($"Error when parsing: {e.Message}");
}
}
}
}
public static class IntegerParser
{
private const int MinDigit = '0';
private const int MaxDigit = '9';
public static bool TryParse(object number, out int result)
{
if (number is int)
{
result = (int)number;
return true;
}
if (number is string)
{
return ParseString((string)number, out result);
}
throw new NotSupportedException($"{nameof(IntegerParser)} only accepts strings ans integers, type '{number.GetType()}' is not supported");
}
private static bool ParseString(string number, out int result)
{
result = 0;
for (var i = 0; i < number.Length; i++)
{
var charCode = (int)number[i];
if (charCode < MinDigit || charCode > MaxDigit)
{
return false;
}
result = result * 10 + (charCode - MinDigit);
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment