Just like the title says.
I\'ve tried doing str.Replace(\"\",\"0\");
but it gave me error because oldValue
has zero length.
Is it possi
You can simply return "0"
for null, zero length or whitespace string using this one-liner:
return String.IsNullOrWhiteSpace(str) ? "0" : str;
You can't replace empty string within the string, but you can replace, say, spaces, e.g.
str = str.Replace(" ", "0"); // providing str is not null
Or you can substitute empty string with "0"
:
if (String.IsNullOrEmpty(str))
str = "0";
When parsing string
into int
you can do something like that:
int x = String.IsNullOrEmpty(str) ? 0 : Convert.ToInt32(str);
In method() you can do:
return String.IsNullOrEmpty(retString) ? "0" : retString;
After your edit:
To convert an empty string to 0
, and parse a non-empty string as an integer, I wouldn't deal with a "0"
at all, but combine the two in a single method. For example:
int Parse(string s, int d = 0) {
if (string.IsNullOrEmpty(s))
return d;
return int.Parse(s);
}