Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting integer from string

Tags:

c#

.net

This might be really simple but i have a service that returns a string that has a number preceded with zeros. The count of zeros is not predictable but i need to extract the number out of the value. The length of the value is also not constant. For ex. 00001234, 002345667, 0000000, 011, 00000987 - in all these values, i need to extract the 1234, 2345667, <no value>, 11, 987. i have tried doing the below code but it returns the zeros as well:

string.Join( null,System.Text.RegularExpressions.Regex.Split( expr, "[^\\d]" ) );

Can anyone help?

Got my Answer::

I got it using stringObj.TrimStart('0'). But i agree using Int.Parse or Int.TryParse is a better way of handling. Hope this is useful to someone like me!

like image 979
user583126 Avatar asked Jul 27 '11 18:07

user583126


3 Answers

int ret;

if (int.TryParse("0001234", out ret))
{
    return ret.ToString();
}

throw new Exception("eep");
like image 121
dkackman Avatar answered Oct 05 '22 23:10

dkackman


var numString = "00001234, 002345667, 0000000, 011, 00000987";

// result will contain "1234, 2345667, <no value>, 11, 987"
var result = string.Join(", ", numString.Split().Select(s => 
    {
        var intVal = int.Parse(s);
        return intVal == 0 ? "<no value>" : intVal.ToString();
    }));
like image 23
Justin Niessner Avatar answered Oct 06 '22 01:10

Justin Niessner


Cast to integer and back to string?

int num    = Convert.ToInt32(val);
string val = Convert.ToString(num);
like image 42
JK. Avatar answered Oct 06 '22 00:10

JK.