检查的最佳方式,如果一个字符数组是空的 [英] Best way to check if a character array is empty

查看:102
本文介绍了检查的最佳方式,如果一个字符数组是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是检查是否一个字符数组是空的最可靠的方法是什么?

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) {}

请告诉我最有效的方式去了解呢?

Whats the most efficient way to go about this?

推荐答案

有鉴于此code:

char text[50];
if(strlen(text) == 0) {}

其次是这个code问题:

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) {}

...的文本[] 将未初始化和未定义的内容。因此,的strlen(文本)将返回一个不确定的结果。

... 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(文本)和极快速但并非如直截了当(文字[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆