How to replace string.empty to “0”

后端 未结 10 1761
无人共我
无人共我 2021-01-27 11:15

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

相关标签:
10条回答
  • 2021-01-27 12:06

    You can simply return "0" for null, zero length or whitespace string using this one-liner:

    return String.IsNullOrWhiteSpace(str) ? "0" : str;
    
    0 讨论(0)
  • 2021-01-27 12:06

    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);
    
    0 讨论(0)
  • 2021-01-27 12:07

    In method() you can do:

    return String.IsNullOrEmpty(retString) ? "0" : retString;
    
    0 讨论(0)
  • 2021-01-27 12:16

    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);
    }
    
    0 讨论(0)
提交回复
热议问题