加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 确定字符串文字的长度

发布时间:2020-12-16 03:24:42 所属栏目:百科 来源:网络整理
导读:给定一个指向字符串文字的指针数组: char *textMessages[] = { "Small text message","Slightly larger text message","A really large text message that " "is spread over multiple lines"} 如何确定特定字符串字面量的长度 – 说第三个字符串?我已经尝
给定一个指向字符串文字的指针数组:
char *textMessages[] = {
    "Small text message","Slightly larger text message","A really large text message that "
    "is spread over multiple lines"
}

如何确定特定字符串字面量的长度 – 说第三个字符串?我已经尝试使用sizeof命令如下:

int size = sizeof(textMessages[2]);

但结果似乎是数组中的指针数,而不是字符串文字的长度.

解决方法

如果你想在编译时计算的数字(而不是在运行时使用strlen),那么使用一个表达式是完全可以的
sizeof "A really large text message that "
       "is spread over multiple lines";

你可能想使用一个宏来避免重复这个长的文字,尽管如此:

#define LONGLITERAL "A really large text message that " 
                    "is spread over multiple lines"

请注意,sizeof返回的值包括终止NUL,因此比strlen多一个.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读