1

I get a string from a 3rd party SW with a long type qualifier, e.g. "1L". I want to parse this to an Int64, but Int64.TryParse does not recognize this as an Int64. Is there a .NET method that does this safely? I want to avoid parsing myself...

Thanks for any help!

user736570
  • 469
  • 4
  • 15
  • 1
    `String.Replace("L","")` ? – I4V Apr 25 '13 at 13:47
  • You replace the `L` (or `l`) if it's 1) Not the first non-whitespace character; and 2) it is the last character or is followed immediately by a whitespace character. – Jim Mischel Apr 25 '13 at 14:51

2 Answers2

1

In the simplest case, you can do this:

string sNum = "1L";
int pos = sNum.IndexOf('L');
if (pos == sNum.Length-1)
{
    sNum = sNum.Substring(0, sNum.Length-1);
}
long num = int64.Parse(sNum);
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • So I don't really understand this conversion, but if the `L` were in the first position, would `Int64.Parse` work? – Mike Perrenoud Apr 25 '13 at 14:56
  • @MichaelPerrenoud: According to the documentation, `Int64.Parse` wants `[whitespace][sign]digits[whitespace]`. There is no allowance for a leading or trailing type specifier. – Jim Mischel Apr 25 '13 at 16:33
  • Now I understand, and so that trailing type specifier (e.g. `L`) isn't really standard and rather just an artifact of where it's coming from. – Mike Perrenoud Apr 25 '13 at 16:58
0

From browsing around, the best I can recommend is using a regular expression to either extract or remove the non numeric characters, and then to parse with the framework (Convert, Parse or TryParse etc).

I poached this from one of the questions below, hope it works:

var originalString = "9L";
var result = Convert.ToInt64(Regex.Replace(originalString, "[^0-9]", String.Empty));

See these questions for some examples (and some, err, ...interesting alternative approaches):

Community
  • 1
  • 1
GrahamMc
  • 3,034
  • 2
  • 24
  • 29
  • Thanks, I hoped I could avoid string manipulation, but this will work. – user736570 Apr 25 '13 at 16:29
  • 1
    So that will make "93foobar265" into "93265"? Fun. – Jim Mischel Apr 25 '13 at 16:34
  • Yep Jim, not the cleanest but the best I could find. The regex could be changed easily enough to only replace L or l (as per your comment) but the OP wasn't really clear about what the constraints or possible positions of the alpha characters could be – GrahamMc Apr 25 '13 at 19:23
  • Incidentally, Jim, I think your answer would handle 93foobar265 by throwing a NumberFormatException? With a modified regex I think this answer would give the same behavior. That would be preferable, if there is some way the incoming string might look something other than alpha + L ... Like OP says would be great if there was a framework method :) – GrahamMc Apr 25 '13 at 19:33