string.empty()

标签:
stringemptyit |
分类: IT |
查了很多资料,终于知道string.empty 与 =="" 是等价的。
7
string s =
"";
8
cout
<< s.empty()
<< endl;
9
s =
"hello";
10
cout
<< s.empty()
<< endl;
11
string s1;
12
cout
<< s1.empty()
<< endl;
13
string s2="\0";
14
cout
<< s2.empty()
<< endl;
15
if(s2 == "")
16
{
17
cout
<< "equal"
<< endl;
18
}
19
else
20
cout
<< "unequal"
<< endl;
21
return 0;
测试:
输出:
$ ./a.out
1
0
1
1
equal
两者的区别在于:(来自网友)
#str.empty()是更普遍。
如果有一天你决定使用`标准::wstring海峡`然后`str.empty()`可以工作,但'海峡==“”`甚至不能编译。
#正常情况下,是的。
但是,如果有人决定重新确定经营者则所有的赌注都关闭:
bool operator == (const std::string& a, const char b[])
{
return a != b; // paging www.thedailywtf.com
}
Answer: 483517
http://1.gravatar.com/avatar/5813f7fcba260d42f01344268d1d2c7f?s=48
它应该是。 的ANSI / ISO国家标准21.3.3 basic_string
容量
size_type size() const;
返回:一个字符串的字符数,如目前在物体。
bool empty() const;
返回:
size() == 0
然而,在第18 basic_string
建设者traits::length()
建立的序列长度的控制,因此最终可能会怪你的东西,如果您使用的是专业化的不同std::basic_string<>
我认为100%正确的陈述是:
(str.empty() == (str == std::string()))
或类似的东西。 如果你还没有做任何事情奇怪,那么std::string("")
和std::string()
应相等于
他们在逻辑上是类似的,但它们是不同的东西测试。 str.empty()
是检查,如果字符串为空字符串的地方,另一个是空的平等检查对一个C风格。
我会用哪个更适合你正在尝试做适当的。 如果你想知道一个字符串是空的,然后使用str.empty()