C Language String
First, the string basis
Note: The string must end with a.
Printf ("yang\n");
Where Yang is a string constant, "yang" = ' y ' + ' a ' + ' n ' + ' g ' + '. Strings consist of a number of characters, usually using a character array to store strings, such as Char name[10]= "Yang", or in the form of printf (name), which is the way to access strings through an array, but there is a warning. Because by default, the printf function accepts only string constants as arguments (not the variables).
Three ways to type a string:
- Char name[8]= "Yang";//Arrays occupy 8 bytes of storage space, but contain only 5 characters.
- Char name[8]={' y ' + ' a ' + ' n ' + ' g ' + ' \o '};
- Char name[8]={' y ' + ' a ' + ' n ' + ' G ' + ' 0 '};
These three types of writing are the same in memory.
Char name[]={' y ' + ' a '}; The preceding number is not written, it is not a string, it can only be said to be an ordinary character array.
Char name[]= "Yang";
name[1]= ' o '; change the value of the second element of the string from a to O.
Second, the use of the string note points
(1) Analyze the code to understand the role of the.
Char name[]= "Yang";
Char name2[]={' o ' + ' k '};
Printf ("name2=%s", name2);
%s: Print the string according to the parameters on the right (until you have encountered a)
The above code prints the result: Okyang
The following is an analysis of memory conditions:
Ask 1:char name[]= "y\0ng"; print the result why? (Oky)
Q 2: Print the value of name at this time, what is the use of%s? Y\0ng or Y?
(2) Strlen function
The Strlen function calculates the length of a string (the number of characters) but does not include the number of characters. For example, a Chinese character occupies three characters.
Strlen ("haha");//Length of 4
Strlen ("ha haha");//Length 7 instead of 5
Set
Char name[]= "It\0cast";
Strlen (name); The value is 2 because Strlen is calculated from the address of the string until it encounters a.
Assume
Char name[]= "Itcast";
Char name2[]={' o ' + ' k '};
Int Size=strlen (name);
The value of size at this time is 8.
(3) Practice, write a function char_contains (char Str[],char c), if the string contains the character C, then return 1, otherwise return 0.
Int Char_contains (char Str[],char c)
{
Traverse the entire string
for (int i=0,i<strlen (str); i++)
{
If (STR[I]==C)
Return 1;
}
Return 0;
}
Invoke statement
Int result=char_contains ("Yang", ' a ');
Using the While loop
①. while (I<strlen (str))
②. while (str[i]!= ')
③. while (Str[i])
④. Int i=-1;while (str[i++])
Three, a string array
A two-dimensional character array that stores two string arrays, each with a length of 1, and the following two types of notation, but the storage is the same.
Char name[2][10]={"Jack", "Rose"};
Char name2[2][10]={
{' J ' + ' a ' + ' C ' + ' K ' + ' + '},
{' R ' + ' O ' + ' s ' + ' e ' + ' + '}
}
Output Rose: printf ("%s", name2[1]);
Output k:printf ("%c", name2[0][3]);
C Language String