各种空字符串的比较与转换
测试代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
static void Main(string[] args) { string[] ss = new string[]{ "", " ", " ", string.Empty }; for (int i = 0; i < ss.Length; i++) { for (int j = i+1; j < ss.Length; j++) { bool re=false; if (ss[i] == ss[j]) re = true; Console.WriteLine("{0}与{1}是否相等{2}", i.ToString(), j.ToString(), re.ToString()); } } Console.ReadLine(); for (int i = 0; i < ss.Length; i++) { try { double p = Convert.ToDouble(ss[i]); Console.WriteLine("{0} {1}", i.ToString(), p.ToString()); } catch (System.Exception ex) { continue; } } Console.ReadLine(); for (int i = 0; i < ss.Length; i++) { try { double p; double.TryParse(ss[i], out p); Console.WriteLine("{0} {1}", i.ToString(), p.ToString()); } catch (System.Exception ex) { continue; } } Console.ReadLine(); }
比较与转化字符串“”,“ ”(一个空格),“ ”(两个空格),string.Empty四个变量
测试结果:
(1)string.Empty=""(无空格),其他的两两不相等
(2)Convert.ToDouble()函数,上述所有的变量都转化不成功,抛出输入字符串的格式不正确的异常
(3)Double.TryParse(ss[i],out p),上述所有的字符串转化为0
判断字符串中的“空格”,而不论其有几个空格
string ss = " ";
if(ss.Trim().Length==0)