Use of C character arrays and strings

Source: Internet
Author: User

1. Definition and initialization of character Arrays
The easiest way to initialize a character array is to assign characters to each element in the array one by one.
Char str [10] = {'I', '', 'A', 'M','', 'h', 'A', 'P ', 'P', 'y '};
Assign 10 characters to str [0] to str [9] and 10 elements respectively.
If the number of characters provided in curly braces is greater than the length of the array, the syntax is used to handle errors. If the number is smaller than the length of the array, only the elements before the character array are, the remaining elements are automatically set to null characters (I .e. '\ 0 ').

2. Character arrays and strings
In C, strings are processed as character arrays. (C ++ is not)
In practical applications, the length of a valid string is concerned rather than the length of a character array. For example, a character array is defined as 100 characters in length, and the actual valid character is only 40 characters, to determine the actual length of a string, the C language specifies a "string end sign", represented by the character '\ 0. If there is a string with 10th characters being '\ 0', the valid character of this string is 9. That is to say, when the first character '\ 0' is encountered, it indicates that the string ends and consists of the characters before it.
The system automatically adds '\ 0' to the String constant as the Terminator. For example, "C Program" has a total of 9 characters, but it occupies 10 bytes in the memory. The last byte '\ 0' is automatically added by the system. (Verified by the sizeof () function)
With the ending sign '\ 0', the length of the character array is not so important. In the program, the length of the character array is often determined by the position of' \ 0, instead of determining the string length based on the array length. Of course, the actual string length should be estimated when defining the character array to ensure that the array length is always greater than the actual length of the string. (In the actual string definition, the array length is often not specified, such as char str [])
Description: '\ N' indicates the character whose ASCII code is 0. From the ASCII code table, we can find that the character whose ASCII code is 0 is not a printable character, but an "null operator ", that is, it does nothing. Using it as the string end flag does not produce additional operations or add valid characters, only one flag for identification.
After learning about how to process strings in C language, you can use string constants to initialize character arrays:
Char str [] = {"I am happy"}; curly braces can be omitted, as shown below:
Char str [] = "I am happy ";
Note:: The overall assignment of the character array can only be used when the character array is initialized. It cannot be used to assign values to character arrays. The assignment of character Arrays can only assign values to its elements one by one, the following assignment method is incorrect.
Char str [];
Str = "I am happy ";

Instead of using a single character as the initial value, it uses a string (note: the two ends of the string are enclosed by double quotation marks "" rather than single quotation marks '') as the initial value. Obviously, this method is more intuitive and convenient. (Note:: The length of the str array is not 10, but 11. Remember this, because the system automatically adds '\ 0' to the end of the string constant "I am happy ')
Therefore, the above Initialization is equivalent to the following Initialization
Char str [] = {'I', '', 'A', 'M','', 'h', 'A', 'P', 'P ', 'y', '\ 0 '};
It is not equivalent to the following
Char str [] = {'I', '', 'A', 'M','', 'h', 'A', 'P', 'P ', 'y '};
The length of the former is 11, and the length of the latter is 10.
Note:The character array does not require its last character to be '\ 0' or even' \ 0'. It is completely legal to write it below.
Char str [5] = {'C', 'h', 'I', 'n', 'A '};
++
It can be seen that the length of the array obtained after the character array is initialized using two different methods is different.

# Include <stdio. h>
Void main (void)
{
Char c1 [] = {'I', '', 'A', 'M','', 'h', 'A', 'P', 'P ', 'y '};
Char c2 [] = "I am happy ";
Int i1 = sizeof (c1 );
Int i2 = sizeof (c2 );
Printf ("% d \ n", i1 );
Printf ("% d \ n", i2 );
}
Result: 10 11

3. String Representation
In C, you can use two methods to represent and store strings:
(1) store a string with a character array
Char str [] = "I love China ";
(2) Use a character pointer to point to a string
Char * str = "I love China ";
For the second expression method, some people think that str is a string variable. It is wrong to assign the String constant "I love China" directly to this string variable during definition.
C language processes string constants by character array. A character array is opened in the memory to store string constants, when defining the string pointer variable str, the program only assigns the first address of the string (that is, the first address of the character array storing the string) to str.
Both representation strings are used for output.
Printf ("% s \ n", str );
% S indicates that a string is output, and str is the character pointer variable name (for the first representation method, the character array name is the first address of the character array, is consistent with the pointer in the second type), the system first outputs a character data to which it points, and then automatically adds 1 to str to point to the next character ..., until the end identifier of the string "\ 0" is encountered ".

4. Discussion on using character pointer variables and character arrays to represent strings
Although character arrays and character pointer variables can be used to store and operate strings, they are different and should not be confused.
4.1 The character array consists of several elements, each containing one character, and the character pointer variable contains the address (the first address of the string/character array ), never put a string in a character pointer variable (it is the first address of the string)
4.2,Assignment Method:
Assign values to character arrays only to each element. Do not assign values to character arrays using the following method:
Char str [14];
Str = "I love China"; (but in the character arrayInitializationYes, that is, char str [14] = "I love China ";)
For character pointer variables, assign values using the following method:
Char *;
A = "I love China ";
Or char * a = "I love China ";
4.3 assign an initial value to the character pointer variable (Initialization):
Char * a = "I love China ";
It is equivalent:
Char *;
A = "I love China ";
Initialization of character Arrays
Char str [14] = "I love China ";
Cannot be equivalent:
Char str [14];
Str = "I love China"; (this assignment is not initialization, but an assignment, but an assignment to an array is incorrect)
4.4 If a character array is defined, it has a fixed memory address. when defining a character pointer variable, it does not point to a fixed character data and can be assigned multiple times.

5. string processing functions
5.1
Char * strcat (char * str1, const char * 2 );
Char * strcat (char * strDestination, const char * strSource );
Function: connects str2 to the end of str1 and returns the str1 pointer.
Note: Each of the first two strings is followed by a '\ 0'. During connection, the' \ 0' following string 1 is removed, and only one '\ 0' is retained at the end of the new string'
5.2
Char * strcpy (char * str1, const char * 2 );
Char * strcpy (char * strDestination, const char * strSource );
Function: copy the character in the strSource string to the strDestination string, including the null end character. The return value is strDestination.
Note: 1. "character array 1" must be written as an array name. "string 2" can be a character array name or a String constant.
2. Copy the string to array 1 together with '\ 0'.
3. A String constant or character array cannot be directly assigned to a character array using a value assignment statement (the same as an ordinary variable array), but can only be processed using the strcpy function.
4. You can use the strcpy function to copy the first several characters in string 2 to character array 1.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.