EN
C#/.NET - parse number algorithm (atoi)
9 points
xxxxxxxxxx
1
public class Parser
2
{
3
public static int parseInt(string text)
4
{
5
if (text.Length > 0)
6
{
7
int value = 0;
8
int total = 1;
9
10
for (int i = text.Length - 1; i > -1; i -= 1)
11
{
12
char entry = text[i];
13
14
if (entry < '0' || entry > '9')
15
throw new FormatException("Incorrect number format.");
16
17
value += (entry - '0') * total;
18
total *= 10;
19
}
20
21
return value;
22
}
23
else
24
throw new FormatException("Incorrect number format.");
25
}
26
}
Usage example:
xxxxxxxxxx
1
string text = "123";
2
int value = Parser.parseInt(text);
3
4
Console.WriteLine(value);
Output:
xxxxxxxxxx
1
123
xxxxxxxxxx
1
public class Parser
2
{
3
public static int parseInt(string text)
4
{
5
if (text.Length > 0)
6
{
7
int value = 0;
8
int total = 1;
9
10
Action<char> action = (entry) =>
11
{
12
if (entry < '0' || entry > '9')
13
throw new FormatException("Incorrect number format.");
14
15
value += (entry - '0') * total;
16
};
17
18
for (int i = text.Length - 1; i > 0; i -= 1)
19
{
20
action.Invoke(text[i]);
21
22
total *= 10;
23
}
24
25
{
26
char entry = text[0];
27
28
switch (entry)
29
{
30
case '+':
31
return +value;
32
33
case '-':
34
return -value;
35
36
default:
37
action.Invoke(entry);
38
39
return value;
40
}
41
}
42
}
43
else
44
throw new FormatException("Incorrect number format.");
45
}
46
}
Usage example:
xxxxxxxxxx
1
string text = "123";
2
int value = Parser.parseInt(text);
3
4
Console.WriteLine(value);
Output:
xxxxxxxxxx
1
123