确定一个字符串文字的长度 [英] Determining the Length of a String Literal

查看:138
本文介绍了确定一个字符串文字的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于指针数组到字符串:

Given an array of pointers to string literals:

char *textMessages[] = {
    "Small text message",
    "Slightly larger text message",
    "A really large text message that "
    "is spread over multiple lines"
}

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

How does one determine the length of a particular string literal - say the third one? I have tried using the sizeof command as follows:

int size = sizeof(textMessages[2]);

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

But the result seems to be the number of pointers in the array, rather than the length of the string literal.

推荐答案

如果你想在计算数量的编译时间的(而不是在运行时用的strlen ),这是完全没关系使用前pression像

If you want the number computed at compile time (as opposed to at runtime with strlen) it is perfectly okay to use an expression like

sizeof "A really large text message that "
       "is spread over multiple lines";

您可能需要使用宏来避免重复长的文字,虽然:

You might want to use a macro to avoid repeating the long literal, though:

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

请注意,通过的sizeof 的返回值包括终止NUL,这样一个超过的strlen

Note that the value returned by sizeof includes the terminating NUL, so is one more than strlen.

这篇关于确定一个字符串文字的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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