How to replace string.empty to “0”

后端 未结 10 1784
无人共我
无人共我 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);
    

提交回复
热议问题