String.Empty,NULL和""的区别

String.Empty,NULL和”“的区别

string.Empty就相当于””
一般用于字符串的初始化
比如:
string a;
Console.WriteLine(a);//这里会报错,因为没有初始化a
而下面不会报错:
string a=string.Empty;
Console.WriteLine(a);
或者用于比较:
if(a==”“)
if(a==string.Empty)
上面两句是一样的效果。

string.Empty不分配存储空间
“”分配一个长度为空的存储空间
所以一般用string.Empty

String.Empty和Null,这两个都是表示空字符串,string str1= String.Empty,这样定义后,str1是一个空字符串,空字符串是一个特殊的字符串,只不过这个字符串的值为空,在内存中是有准确的指向的 ,*string str2=null,这样定义后,只是定义了一个string 类的引用,str2并没有指向任何地方,在使用前如果不实例化的话,都将报错*

textBox1.Text的值为零长度字符串 “”。
判定为空字符串的几种写法,按照性能从高到低的顺序是:
s.Length == 0 优于 s == string.Empty 优于 s == “”

判断字符串是否为空最好的方法就是 s.Length==0 !

下面列一段string的empty,size,length等比较代码

#include<iostream>
#include<string>

using namespace std;

void Display(const string& str)
{
    cout<<"String: "<<str<<endl;
    cout<<"Empty: "<<str.empty()<<endl;
    cout<<"Size: "<<str.size()<<endl;
    cout<<"Length: "<<str.length()<<endl;
    cout<<"Capacity: "<<str.capacity()<<endl;
    cout<<"Maxsize: "<<str.max_size()<<endl;
    cout<<endl;
}


int _tmain(int argc, _TCHAR* argv[])
{
    string s1="";  //无字节
    Display(s1);

    string s2="  ";  //两个空子节
    Display(s2);

    string s3="123456";
    Display(s3);

    string s4="123 456 asd";
    Display(s4);

   /* s3.resize(23);
    Display(s3);*/

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/programer_vc/article/details/78905404