Search code examples
c#string.net-2.0

getting number from string


How I can get number from following string:

###E[shouldbesomenumber][space or endofline]

[] here only for Illustration not present in the real string.

I am in .net 2.0.

Thanks.


Solution

  • I would suggest that you use regular expressions or string operations to isolate just the numeric part, and then call int.Parse, int.TryParse, decimal.Parse, decimal.TryParse etc depending on the type of number you need to parse.

    The regular expression might look something like:

    @"###E(-?\d+) ?$";
    

    You'll need to change it for non-integers, of course. Sample code:

    using System;
    using System.Text.RegularExpressions;
    
    class Test
    {
        static void Main(string[] arg)
        {
            Regex regex = new Regex(@"###E(-?\d+) ?$");        
            string text = "###E123 ";
    
            Match match = regex.Match(text);
            if (match.Success)
            {
                string group = match.Groups[1].Value;
                int parsed = int.Parse(group);
                Console.WriteLine(parsed);
            }
        }
    }
    

    Note that this could still fail with a number which exceeds the range of int. (Another reason to use int.TryParse...)