简体   繁体   English

获取字符数组的长度

[英]Getting length of character array

I know other questions have been asked about this topic but I could not find one for exactly what I am looking for. 我知道有关此主题的其他问题已经提出,但我找不到正要寻找的问题。 I am taking a course on C and was presented with the following challenge: "Create a new application and create four character arrays to hold the following lines of text: 我正在学习C语言课程,并面临以下挑战:“创建一个新应用程序,并创建四个字符数组来保存以下文本行:

'Roses are Red. '玫瑰是红色的。 Violets Are Blue. 紫罗兰是蓝色的。 C Programming is Fun. C编程很有趣。 And Sometimes Makes my Head Hurt.' 有时会让我头疼。 Make sure your character arrays are large enough to accommodate the character used to terminate C strings. 确保您的字符数组足够大以容纳用于终止C字符串的字符。 Using a correctly formatted printf() command and signifier, output the string array values. 使用格式正确的printf()命令和符号,输出字符串数组值。 "

Here is the code I have so far: 这是我到目前为止的代码:

#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";
}

Instead of manually counting the number of characters in each array and then putting that number in the "[]", is there a way to determine the length of character in each string? 除了手动计算每个数组中的字符数,然后将该数字放入“ []”中之外,还有什么方法可以确定每个字符串中的字符长度?

The syntax: 语法:

char str[] = "Some text.";

already counts the right length for the string . 已经计算出字符串的正确长度。 You don't have to take any further action. 您无需采取任何进一步的措施。 Leaving the [] empty (in this context) means that the array has the exact size required to store the string. []保留为空(在此上下文中)意味着该数组具有存储字符串所需的确切大小。

You can inspect this by doing printf("The size is %zu.\\n", sizeof str); 您可以通过执行printf("The size is %zu.\\n", sizeof str); , note that this will be 1 more than the result of strlen because strings have a null terminator. ,请注意,这比strlen的结果大1 ,因为字符串具有空终止符。

Based on my research by using strlen 根据我对strlen研究

Code: 码:

#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);
}

output: 输出:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM