I would like to get number from a string eg: My123number gives 123 Similarly varchar(32) gives 32 etc
Thanks in Advance.
I would like to get number from a string eg: My123number gives 123 Similarly varchar(32) gives 32 etc
Thanks in Advance.
If there is going to be only one number buried in the string, and it is going to be an integer, then something like this:
int n;
string s = "My123Number";
if (int.TryParse (new string (s.Where (a => Char.IsDigit (a)).ToArray ()), out n)) {
Console.WriteLine ("The number is {0}", n);
}
To explain: s.Where (a => Char.IsDigit (a)).ToArray ()
extracts only the digits from the original string into an array of char. Then, new string
converts that to a string and finally int.TryParse
converts that to an integer.
Loop through each char in the string and test it for being a number. remove all non-numbers and then you have a simple integer as a string. Then you can just use int.parse.
string numString;
foreach(char c in inputString)
if (Char.IsDigit(c)) numString += c;
int realNum = int.Parse(numString);
var s = "varchar(32)";
int value = int.Parse(new string(s.Where(c => Char.IsDigit(c)).ToArray()));
You could do something like this, then it will work with more then one number as well
public IEnumerable<string> GetNumbers(string indata)
{
MatchCollection matches = Regex.Matches(indata, @"\d+");
foreach (Match match in matches)
{
yield return match.Value;
}
}
you could go the regular expression way. which is normally faster than looping through the string
public int GetNumber(string text)
{
var exp = new Regex("([0-9])+"); // find a sequence of digits could be \d+
var matches = exp.Matches(text);
if (matches.Count == 1) // if there's one number return that
{
int number = int.Parse(matches[0].Value);
return number
}
else if (matches.Count > 1)
throw new InvalidOperationException("only one number allowed");
else
return 0;
}
First write a specification of what you mean by a "number" (integer? long? decimal? double?) and by "get a number from a string". Including all the cases you want to be able to handle (leading/trailing signs? culture-invariant thousands/decimal separators, culture-sensitive thousands/decimal separators, very large values, strings that don't contain a valid number, ...).
Then write some unit tests for each case you need to be able to handle.
Then code the method (should be easy - basically extract the numeric bit from the string, and try to parse it. Some of the answers provided so far will work for integers provided the string doesn't contain a value larger than Int32.MaxValue).