In C language programming, we typically use a character array to hold a string. For example, we want to store the string "http://i.cnblogs.com", which has a total of 20 characters, to hold the string, we need a 21-length character array. Why 21 instead of 20? In the C language, the array of strings is terminated by default, so we need a character array of length 21 to store the variable.
unsigned char text[21] = "http://i.cnblogs.com";
Now that we know how to store a string, let's discuss a few other issues. First, a character array is known to hold a string, how long does it solve the string? To solve this problem, we should start with the storage principle of string. In the previous article, we have known that the character at the end of the storage string is ' \ s ', then we can use the loop to scan the character array to scan the ' s ' as the end flag, thus solving the length of the string.
unsigned char get_text_length (unsigned char *sp)
{
unsigned char text_length=0;
while (*SP)/* Determines if the character is ' \ s ' */
{
text_length++;
*sp++; /* Point to the next one in the array */
}
return text_length;
}
Furthermore, with regard to the initialization of character arrays, can we use double quotation marks to directly assign values to strings while declaring the array of characters, and is there any other way?
Method One:
unsigned char text[] = "www.google.com";
Method Two:
unsigned char text[20];
strcpy (text, "www.google.com");
Note that method two calls the system function strcpy (), which is defined in string.h.