This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging

Character array

The array used to hold the characters is called a character array. The form of the character array type description is the same as that of the numeric array described earlier.

Char c[10]; Since characters and integers are common, we can also define it as int C [10], but in this case, each array element occupies 2 bytes of memory.

Character arrays can also be two-dimensional or multidimensional, for example: char c[5][10]; That’s a two-dimensional array of characters.

Character arrays also allow initialization assignments on type description.

Such as:

 static char c[10]={`c`,` `,`p`,`r`,o`,g`,r`,`a`,`m`};
Copy the code

The values of each element are as follows: array C C [0] C [1] C [2] C [3] C [4] C [5] C [6] C [7] C [8] C [9] Where C [9] is not assigned, and the system automatically assigns 0 value to it. You can also omit the length description when assigning an initial value to all elements.

Such as:

static char c[]={`c`,` `,`p`,`r`,`o`,`g`,`r`,`a`,`m`};
Copy the code

The length of the C array is automatically set to 9.

main()
{
int i,j;
char a[][5] = {{'B'.'A'.'S'.'I'.'C'}, {'d'.'B'.'A'.'S'.'E'}};
for(i=0; i<=1; i++) {for(j=0; j<=4; j++)printf("%c",a[i][j]);
printf("\n"); }}Copy the code

Since all the elements are initialized with initial values, the length of the one-dimensional subscript can be left unstated for the two-dimensional character array in this example. String There is no special string variable in C language, usually a character array is used to store a string.

When we introduced string constants earlier, we explained that strings always end with ‘\0’. So when you store a string into an array, you also store the terminator ‘\0’ into the array to indicate whether the string is over. With the ‘\0’ flag, you no longer need to use the length of the character array to determine the length of the string. C allows you to initialize an array as a string. Such as:

static char c[]={'c'.' '.'p'.'r'.'o'.'g'.'r'.'a'.'m'}; Can be written as:static char c[]={"C program"}; Or remove {} and write: sraticchar c[]="C program";
Copy the code

String assignments take up one byte more than character-by-character assignments and are used to store the end-of-string flag ‘\0’. C program\0 ‘\0’ is automatically added by the C compilation system.

Since the ‘\0’ flag is used, it is generally not necessary to specify the length of the array when assigning the initial value of the string, and the system handles it by itself. With the use of strings, the input and output of character arrays becomes simple and convenient. In addition to the above method of assigning initial values to strings, you can use the printf and scanf functions to output the strings in a character array at once, rather than using a loop to input and output each character individually.

void main(a)
{
static char c[]="BASIC\ndBASE";
printf("%s\n",c);
}
Copy the code

Note that in the printf function in this example, the format string “%s” is used to indicate that the output is a string. Instead, give the array name in the output table column. Printf (“%s”,c[]);

void main(a)
{
char st[15];
printf("input string:\n");
scanf("%s",st);
printf("%s\n",st);
}
Copy the code

Since the array length is defined as 15 in this example, the input string must be less than 15 to leave one byte for the \0 end-of-string flag. It should be noted that if you do not initialize an array of characters, you must specify the array length. It should also be noted that when entering a string using the scanf function, the string must not contain a space, otherwise the string will end with a space. For example, in example 4.8, when the input string contains Spaces, the command output is as follows: input string:this is a book this The output results show that no characters after Spaces are printed. To avoid this, set more character arrays to compartmentalize strings containing Spaces. The program can be rewritten as follows:

Lesson
void main(a)
{
char st1[6],st2[6],st3[6],st4[6];
printf("input string:\n");
scanf("%s%s%s%s",st1,st2,st3,st4);
printf("%s %s %s %s\n",st1,st2,st3,st4);
}
Copy the code

This program sets up four arrays, and the space segments of the input line of characters are loaded into four arrays respectively. Then print out the strings in each of the four arrays. As mentioned earlier, each entry of Scanf must appear as an address, such as &a,&b, etc. But in example 4.8, it appears as an array name. Why? This is because the C language specifies that the array name represents the first address of the array. The entire array is a contiguous block of memory beginning with the first address. If there is a character array char C [10], it can be represented in memory as shown in Figure 4.2. Let the first address of array C be 2000, that is, the address of cell C [0] is 2000. Then the array name c represents the first address. Therefore, the address operator & cannot be added before c. Such as writing the scanf (” % s “, & c); Is wrong. Printf (“%s”,c) finds the first address by the array name c and prints each character in the array until the string terminating flag ‘\0’ is encountered.

Two, string commonly used functions

C language provides a wealth of string processing functions, can be roughly divided into string input, output, merge, modify, compare, transform, copy, search several categories. Using these functions can greatly reduce the programming burden. String functions used for input and output should include the header “stdio.h” before use; Other string functions should include the header “string.h”. Here are some of the most common string functions.

2.1 puts function

The string output function puts

Format: puts (character array name)

Function: Output a string from a character array to the display. Displays the string on the screen

#include"stdio.h"
main()
{
static char c[]="BASIC\ndBASE";
puts(c);
}

Copy the code

You can see from the program that escape characters can be used in the puts function, so the output becomes two lines.

The puts function can be completely replaced by the printf function. The printf function is usually used when you need to output in a certain format.

2.2 gets function

The string input function gets

Format: gets (string array name)

Function: Input a string from the keyboard of the standard input device.

This function gets a function value, which is the first address of the character array.

#include"stdio.h"
main()
{
char st[15];
printf("input string:\n");
gets(st);
puts(st);
}
Copy the code

As you can see, when the input string contains Spaces, the output is still the full string. The gets function does not end with a space, but only with a carriage return. This is different from the scanf function.

2.3 strcat function

The string concatenation function strcat

Format: strcat (string 1, string 2)

Function: concatenate a string in array 2 to the end of a string in array 1, and delete the string flag “\0” after string 1.

The return value is the first address of the character array 1.

#include"string.h"
main()
{
static char st1[30] ="My name is ";
int st2[10];
printf("input your name:\n");
gets(st2);
strcat(st1,st2);
puts(st1);
}
Copy the code

This program concatenates an initialized assignment character array with a dynamically assigned string. Note that the character array 1 should be defined to a sufficient length, otherwise the concatenated string cannot all be loaded

2.4 strcpy format

String copy function strcpy

Format: strcpy (array 1, array 2)

Function: copy a string from character array 2 into character array 1. The string end flag “\0” is also copied. The number of characters is 2, or it can be a string constant. This is equivalent to assigning a string to a character array.

#include"string.h"
main()
{
static char st1[15],st2[]="C Language";
strcpy(st1,st2);
puts(st1);printf("\n");
}
Copy the code

This function requires that the character array 1 be of sufficient length, otherwise it cannot all load the copied string.

2.5 STRCMP format

The string comparison function STRCMP

Format: STRCMP (array 1, array 2)

Function: compares strings in two arrays in ASCII order and returns the result from the function return value. String 1 = string 2, return value = 0; String 2 > string 2, return value > 0; String 1 < string 2, return value < 0. This function can also be used to compare two string constants, or to compare arrays and string constants.

#include"string.h"
main()
{ int k;
static char st1[15],st2[]="C Language";
printf("input a string:\n");
gets(st1);
k=strcmp(st1,st2);
if(k==0) printf("st1=st2\n");
if(k>0) printf("st1>st2\n");
if(k<0) printf("st1<st2\n");
}
Copy the code

In this program, the input string and array st2 in the string comparison, the comparison result returned to k, according to the value of K output results prompt string. When the input is dbase, we can see from the ASCII code that “dbase” is greater than “C Language”, so k > 0, and the output is “ST1 > ST2”.

2.6 strlen format

The string length function strlen

Format: strlen(character array name)

Function: Measures the actual length of the string (without the end-of-string flag ‘\0’) and returns it as a function value.

#include"string.h"
main()
{ int k;
static char st[]="C language";
k=strlen(st);
printf("The lenth of the string is %d\n",k);
}

Copy the code

2.7 Program Examples

To insert an integer in size order into an sorted array. To insert a number into an sorted array by size, first determine whether the sort is large to small or small to large. If the sort is sorted from large to small, then the number to be inserted can be compared with each number in the array one by one. When the first element I smaller than the insertion number is found, the element before it is the insertion position. It then moves one unit at a time from the last element of the array to that element. Finally, just give the insert number to element I. If the number to be inserted is smaller than all the element values, insert the last position.

main()
{
int i,j,p,q,s,n,a[11] = {127.3.6.28.54.68.87.105.162.18};
for(i=0; i<10; i++) { p=i; q=a[i];for(j=i+1; j<10; j++)if(q<a[j]) {p=j; q=a[j]; }if(p! =i) { s=a[i]; a[i]=a[p]; a[p]=s; }printf("%d ",a[i]);
}
printf("\ninput number:\n");
scanf("%d",&n);
for(i=0; i<10; i++)if(n>a[i])
{for(s=9; s>=i; s--) a[s+1]=a[s];
break; } a[i]=n;for(i=0; i<=10; i++)printf("%d ",a[i]);
printf("\n");
}
Copy the code

This program first on the array a of 10 numbers from large to small sort and output sort results. Then enter the integer n to insert. If n>a[I] is found, an inner loop moves the values of each element below I one cell in order. The backward movement should proceed backward and forward (from a[9] to a[I]). Exit the outer loop after moving back. Insert point I and assign n to a[I]. If all elements are greater than the number to be inserted, no backshift is performed. When I =10, the result is to assign n to a[10]. The last loop prints the values of the elements of the array after the inserted number. When the program runs, enter 47. From the results you can see that 47 has been inserted between 54 and 28.

Select the largest element of each row in the two-dimensional array A to form a one-dimensional array B. A =3 16 87 65 4 32 11 108 10 25 12 37b=(87 108 37) a=3 16 87 65 4 32 11 108 10 25 12 37b=(87 108 37) The procedure is as follows:

main()
{
static int a[][4] = {3.16.87.65.4.32.11.108.10.25.12.27};
int b[3],i,j,l;
for(i=0; i<=2; i++) { l=a[i][0];
for(j=1; j<=3; j++)if(a[i][j]>l) l=a[i][j]; b[i]=l; }printf("\narray a:\n");
for(i=0; i<=2; i++) {for(j=0; j<=3; j++)printf("%5d",a[i][j]);
printf("\n"); }printf("\narray b:\n");
for(i=0; i<=2; i++)printf("%5d",b[i]);
printf("\n");
}
Copy the code

The first for statement in the program is nested with another for statement to form a double loop. The outer loop controls row by row and assigns the 0th column element of each row to L. After entering the inner loop, l is compared to the following columns, and any greater than L is assigned to L. L is the largest element in the row at the end of the inner loop, and l is assigned to b[I]. By the time the loop is complete, array B has loaded the maximum number of lines in a. The next two for statements print array A and array B, respectively.

Enter the names of the five countries and output them alphabetically. Five country names should be treated by a two-dimensional character array. However, THE C language states that you can treat a two-dimensional array as if it were multiple one-dimensional arrays. So this can be treated as five one-dimensional arrays, and each one-dimensional array is a string of country names. Use the string comparison function to compare the size of each one-dimensional array, and sort, output results can be. The programming is as follows:

void main(a)
{
char st[20],cs[5] [20];
int i,j,p;
printf("input country's name:\n");
for(i=0; i<5; i++)gets(cs[i]);
printf("\n");
for(i=0; i<5; i++) { p=i;strcpy(st,cs[i]);
for(j=i+1; j<5; j++)if(strcmp(cs[j],st)<0) {p=j;strcpy(st,cs[j]); }if(p! =i) {strcpy(st,cs[i]);
strcpy(cs[i],cs[p]);
strcpy(cs[p],st);
}
puts(cs[i]); }printf("\n");
}

Copy the code

In the first for statement of this program, the gets function is used to enter five country strings. Cs [5][20] is a two-dimensional character array, which can be divided into five one-dimensional arrays cs[0], cs[1], cs[2], cs[3], cs[4]. It is therefore legal to use cs[I] in the gets function. The second for statement is nested with another for statement to form a double loop. This double loop does the alphabetical work. In the outer loop, copy the country string from the character array cs[I] into the array st, and assign the subscript I to P. After entering the inner loop, st is compared with every string after cs[I]. If any string is smaller than st, the string is copied into st and its subscript is assigned to p. If p does not equal I after the loop is complete, a smaller string than cs[I] occurs, so swap the contents of cs[I] and st. The sort value for the ith element of the array cs is now determined. The string is then printed. All sorting and output is completed when the outer loop is complete.

Iii. Summary of this chapter

  1. Arrays are the most commonly used data structures in programming. Arrays can be divided into numeric arrays (integer groups, real groups), character arrays, and later pointer arrays, structure arrays, and so on.

  2. Arrays can be one-dimensional, two-dimensional, or multidimensional.

  3. The array type description consists of the type descriptor, array name, and array length (number of array elements). Array elements are also called subscript variables. The type of an array is the type of the value of the subscript variable.

  4. Assignment to an array can be accomplished in three ways: array initialization assignment, input function dynamic assignment, and statement assignment. You cannot assign, input, or output an array of values as a whole with an assignment statement. Instead, you must loop through the array element by element.