Say I have a string such as "20 Boxes" and I want to extract the number from that string as an integer to carry out some calculations on it. How should I go about this?
I'm used to using parseInt, but in Unity (unlike in JS) that won't accept any string that contains letters, so that's out unless I split the string up first. If I do have to split the string up first, what's the most efficient way to do so?
Remember to add the Using directive for the .NET Regex class:
using System.Text.RegularExpressions;
I would also like to point out, before all the Webplayer-lovers hound me for it, that the RegularExpressions library adds about 900k to the web player download, so if this is unacceptable for you, don't use Regex. ;)
string sentence = “10 cats, 20 dogs, 40 fish and 1 programmer.”;
string[] digits= Regex.Split(sentence, @"\D+");
foreach (string value in digits)
{
int number;
if (int.TryParse(value, out number))
{
Debug.Log(value);
}
}
Since I was in need of something similar adding this solution for future reference!