How to replace string.empty to “0”

后端 未结 10 1760
无人共我
无人共我 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 11:49

    It sounds like your best option would be int.TryParse, if you encounter a string that can't be set to a valid value, it will set it to the default value for an integer (0) as well as returning a boolean so you can know this has happened.

    int myInt;
    if(!int.TryParse(myStringVariable, out myInt))
    {
        //Invalid integer you can put something here if you like but not needed
        //myInt has been set to zero
    }
    
    //The same code without the if statement, still sets myInt
    int.TryParse(myStringVariable, out myInt);
    
    0 讨论(0)
  • 2021-01-27 11:54

    If you know that str is empty then you may use star="a" If you want to check then write statement in if condition.

    0 讨论(0)
  • 2021-01-27 11:58

    String.Replace takes two string arguments oldValue and newValue. You specified the newValue 0 however an empty string is not legal for the oldValue.

    try below code :-

    str.Replace(" ","0"); 
    

    or you can just assign "0" to emptry string as below :-

    if(str == string.Empty)
    {
       str = "0";
    }
    

    or making it simple :-

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

    It is not possible to replace string.Empty by "0". It will throw ArgumentException.

        An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll.
    Additional information: String cannot be of zero length.
    

    You can try following code:

    if(retString == string.Empty)
    {
    retString = "0";
    }
    
    0 讨论(0)
  • 2021-01-27 12:04

    Try This...

    public string Method1()
    {
          string retString = string.Empty;
          //Do Something
          return string.IsNullOrEmpty(retString)?"0":retString;
    }
    
    0 讨论(0)
  • 2021-01-27 12:05

    If you want to check if the value is empty and then set the value to zero, otherwise use the default value you can use an inline if like so:

    return string.IsNullOrWhiteSpace(retString ) ? "0" : retString;
    
    0 讨论(0)
提交回复
热议问题