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:
'Roses are Red. Violets Are Blue. C Programming is Fun. And Sometimes Makes my Head Hurt.' Make sure your character arrays are large enough to accommodate the character used to terminate C strings. Using a correctly formatted printf() command and signifier, output the string array values. "
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);
, note that this will be 1
more than the result of strlen
because strings have a null terminator.
Based on my research by using 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.