I have a requirement to find and extract a number contained within a string.
For example, from these strings:
string test = \"1 test\"
string test1 =
Extension method to get all positive numbers contained in a string:
public static List Numbers(this string str)
{
var nums = new List();
var start = -1;
for (int i = 0; i < str.Length; i++)
{
if (start < 0 && Char.IsDigit(str[i]))
{
start = i;
}
else if (start >= 0 && !Char.IsDigit(str[i]))
{
nums.Add(long.Parse(str.Substring(start, i - start)));
start = -1;
}
}
if (start >= 0)
nums.Add(long.Parse(str.Substring(start, str.Length - start)));
return nums;
}
If you want negative numbers as well simply modify this code to handle the minus sign (-
)
Given this input:
"I was born in 1989, 27 years ago from now (2016)"
The resulting numbers list will be:
[1989, 27, 2016]