检查字符数组是否为空的最佳方法 [英] Best way to check if a character array is empty
问题描述
检查字符数组是否为空最可靠的方法是什么?
Which is the most reliable way to check if a character array is empty?
char text[50];
if(strlen(text) == 0) {}
或
if(text[0] == '\0') {}
或者我需要做什么
memset(text, 0, sizeof(text));
if(strlen(text) == 0) {}
最有效的方法是什么?
推荐答案
鉴于此代码:
char text[50];
if(strlen(text) == 0) {}
接着是关于此代码的问题:
Followed by a question about this code:
memset(text, 0, sizeof(text));
if(strlen(text) == 0) {}
我闻到了困惑的味道.具体来说,在这种情况下:
I smell confusion. Specifically, in this case:
char text[50];
if(strlen(text) == 0) {}
... text[]
的内容将是未初始化和未定义的.因此,strlen(text)
将返回一个未定义的结果.
... the contents of text[]
will be uninitialized and undefined. Thus, strlen(text)
will return an undefined result.
确保将 C 字符串初始化为空字符串的最简单/最快的方法是简单地将第一个字节设置为 0.
The easiest/fastest way to ensure that a C string is initialized to the empty string is to simply set the first byte to 0.
char text[50];
text[0] = 0;
从那时起,strlen(text)
和非常快但不直接的 (text[0] == 0)
测试都将检测空字符串.
From then, both strlen(text)
and the very-fast-but-not-as-straightforward (text[0] == 0)
tests will both detect the empty string.
这篇关于检查字符数组是否为空的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!