在 C++ 替代方案中检查空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41425569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking for empty string in C++ alternatives
提问by fgalan
There are (at least :) two ways of checking if an string is empty in C++, in particular:
在 C++ 中有(至少 :)两种检查字符串是否为空的方法,特别是:
if (s.length() == 0) {
// string is empty
}
and
和
if (s == "") {
// string is empty
}
Which one is the best from a performance point of view? Maybe the library implementation is clever enough so there isn't any different between them (in which case other criteria should decide, i.e. readibility) but I tend to think that the first alternative (using length()
) is better.
从性能的角度来看,哪个是最好的?也许库的实现足够聪明,所以它们之间没有任何区别(在这种情况下应该由其他标准决定,即可读性),但我倾向于认为第一个选择(使用length()
)更好。
Any feedback on this, please? (Or even a 3rd method better than the ones I have proposed).
请对此有任何反馈吗?(或者甚至是比我提出的方法更好的第三种方法)。
回答by artm
You can also use empty
你也可以使用 empty
if(s.empty())
回答by fgalan
You can use the following:
您可以使用以下内容:
s.empty();
s.size() == 0;
!s.size();