2014-09-01 103 views
-1

我知道关于此主题的其他问题已被询问,但我无法找到正确的我正在寻找的。我服用一个疗程就℃,并出现以下挑战:“创建一个新的应用程序并创建四个字符数组 包含文本以下行:获取字符数组的长度

“玫瑰是红色的 紫罗兰是蓝色的 ℃。编程很有趣,有时让我头痛。“ 确保您的字符数组足以 大容纳用于终止C字符串的字符。 使用正确格式化的printf()命令,并指, 输出字符串数组值。 “

这里是我的代码迄今为止:

#include <stdio.h> 

int main() 
{ 

    char firstLine [] = "Roses are red."; 
    char secondLine [] = "Violets are blue."; 
    char thirdLine [] = "C programming is fun"; 
    char fourthLine [] = "And sometimes makes my head hurt"; 
} 

除了手动计数的字符数在每个阵列中,然后把该号码在“[]”,是有一种方法来确定字符的每个串的长度的?

+0

贾斯汀,下面的其他评论,得到编译你的代码的**好习惯**在你的编译字符串中启用**警告。至少,像'gcc -Wall -Wextra -o outputfile inputfile.c' – 2014-09-02 03:42:09

回答

1

使用strlen

代码根据我的研究:

#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char str [] = "Roses are red."; 
    size_t len; 

    len = strlen(str); 
    printf("Length of |%s| is |%zu|\n", str, len); 
    return(0); 
} 

输出:

Length of |Roses are red.| is |14| 

来源: http://www.gnu.org/software/libc/manual/html_node/String-Length.html

+1

注意:'strlen(str)'返回类型'size_t',而不是'int'。 – chux 2014-09-02 00:41:31

+0

@chux我的回答是错误的? – 2014-09-02 00:42:32

+0

当字符串很小时,您不会遇到差异。在这个例子中 - >没问题。对于一般的解决方案,是的,有一个问题。 – chux 2014-09-02 00:44:57

3

语法:

char str[] = "Some text."; 

已经计算出字符串的正确长度。你不必采取任何进一步的行动。将[]留空(在此上下文中)意味着该数组具有存储字符串所需的确切大小。

您可以通过执行printf("The size is %zu.\n", sizeof str);检查此,请注意,这将比strlen的结果多1,因为字符串具有空终止符。