views:

172

answers:

6

I would like to get number from a string eg: My123number gives 123 Similarly varchar(32) gives 32 etc

Thanks in Advance.

+6  A: 

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.

Tarydon
Good solution but,little complex and there is no s.Where support in vb.net
Thunder
@Thunder. There is `s.Where` support in Vb.net, check the VB example on this page http://msdn.microsoft.com/en-us/library/bb534803(VS.95).aspx
MarkJ
+2  A: 

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);
TheSean
You'll have to initialize numString first (numString = "").
Tarydon
'vb implementationDim numString As String="0"For Each c As Char In inputString If [Char].IsDigit(c) Then numString += c End IfNextDim realNum As Integer = Integer.Parse(numString)
Thunder
string numString="0"; initialization is good as it will give 0 if there is no numbers
Thunder
in the case of a malformed input like the23foo42 this will return 2342 whereas an exception would be appropriate since it's an exceptional situation and there's with the specs given no way of knowing what to return
Rune FS
@Thunder: Nice, like the idea about init to "0".
TheSean
The only issue I have with this is that that the string "a1b2c3d4" will result in the value 1234.
Babak Naffas
A: 
var s = "varchar(32)";
int value = int.Parse(new string(s.Where(c => Char.IsDigit(c)).ToArray()));
Steven
+1  A: 

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;
    }
}
Mikael
match.Value is a string so why convert it to string?
Rune FS
Good point, there is no need. Got the idea that Value would be an object when I wrote the reply, I have updated the reply to reflect this.Thanks for pointing that out.
Mikael
+2  A: 

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;
        }
Rune FS
A: 

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).

Joe
+1 It's impossible to answer this question properly without knowing those things.
MarkJ