-3

Using C#, I need to convert a substring to an int even if the value of the substring is null.

My code reads lines of a text file and then assigns certain parts of the text to strings.

int _CUSTBAL = Convert.ToInt32(line.Substring(5, 2));

Example Text:

12345 10 etc
12346 20 etc
12347      etc

The issue I'm having is that if the line contains a blank space it throws an exception. I need it to return zero if the substring contain a blank. For example. If the text is formatted blank9 then I need to return 09. I've tried using nullable types but that doesn't do the trick. Thanks

Bobby Turkalino
  • 111
  • 2
  • 14
  • 1
    String.Replace(" ", "0") should work to remove blanks and place a zero there. – Sorceri Dec 22 '14 at 20:23
  • What do you mean by "return 09"? Convert.ToInt32() returns int. Do you mean you need string representation? not int? – Paul Dec 22 '14 at 20:24
  • it's not clear what you mean by 090, there is no such number. you can't have leading zeros in an integer. – Selman Genç Dec 22 '14 at 20:24
  • there's too many unknowns. In one of your examples you want 3 digits, which contradicts the rest of the question. And you can't have leading zeros in an `int` type. Figure out what you want. – Jonesopolis Dec 22 '14 at 20:29
  • Bobby search before asking so you don't get downvotes, believe me on that – niceman Dec 22 '14 at 22:04

4 Answers4

3

If TryParse() fails, _CUSTBAL will be 0.

int _CUSTBAL;
int.TryParse(line.Substring(5, 2), out _CUSTBAL);

Here is a fiddle demonstrating your test cases.

And if you really do want leading zeros, _CUSTBAL.ToString("000") will turn, for example, 2 to 002 and 20 to 020.

Tom
  • 7,640
  • 1
  • 23
  • 47
1

What about this:

string sub = line.Substring(5, 2).Trim();
int _CUSTBAL = sub != string.Empty ? Convert.ToInt32(sub) : 0;

It takes away all whitespaces and returns 0 for an empty string.

or else:

string sub = line.Substring(5, 2);
int _CUSTBAL = !string.IsNullOrWhiteSpace(sub) ? Convert.ToInt32(sub) : 0;
Flat Eric
  • 7,971
  • 9
  • 36
  • 45
  • your second option is perfect. Thanks – Bobby Turkalino Dec 22 '14 at 20:35
  • @BobbyTurkalino, one thing I'd point out about `ToInt32` vs `TryParse`, is if `sub` ends up being something other than a null reference or a number, e.g. ` E` or something, you will get a `FormatException` -- `TryParse` will give you a 0 for anything that isn't a number, whether it's a null reference, letters, etc. See [this](http://stackoverflow.com/a/15895040/3199927) post – Tom Dec 22 '14 at 23:28
0

You need to do that yourself.

string toConvert;

if(string.IsNullOrWhiteSpace(line))
    toConvert = "0";
else
    toConvert = line;

Convert.ToInt32(toConvert);
pquest
  • 3,151
  • 3
  • 27
  • 40
0

Why don't you check for blank value?

var value = line.Substring(5, 2);
var _CUSTBAL = String.IsNullOrEmpty(value)? 0 : Convert.ToInt32(value);
Azhar Khorasany
  • 2,712
  • 16
  • 20