extracting integer from string
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. T开发者_开发百科he 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!
int ret;
if (int.TryParse("0001234", out ret))
{
    return ret.ToString();
}
throw new Exception("eep");
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();
    }));
Cast to integer and back to string?
int num    = Convert.ToInt32(val);
string val = Convert.ToString(num);
This should do the trick
string s = "0005";
string output = Convert.ToInt32(s.TrimStart(Convert.ToChar("0")));
The power of regular expressions to the rescue!
static readonly Regex rx = new Regex( @"[^\d]*((0*)([1-9][0-9]*)?)" ) ;
public static IEnumerable<string> ParseNumbers( string s )
{
  for ( Match matched = rx.Match(s) ; matched.Success ; matched = matched.NextMatch() )
  {
    if ( matched.Groups[1].Length > 0 )
    {
      yield return matched.Groups[3].Value ;
    }
  }
}
Passing the string "00001234, 002345667, 0000000, 011, 00000987" to ParseNumbers() yields the enumeration
- "1234"
- "2345667"
- ""
- "11"
- "987"
Cheers!
000000 is 0 not null....
int intInteger = -1;
int.tryparse(stringNumber,out intInteger);
should give you a clean integer.
you can use Int.Parse to parse the string into an integer.
    String s = "00001234, 002345667, 0000000, 011, 00000987";
    string[] nums= s.Split(',');
foreach (string num in nums
{
    Console.WriteLine(Int.Parse(num)); //you'll need special handling to print "<no value>" when the string is 0000000
}
(haven't actually compiled this)
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论