Moät soá kieán thöùc cô sôû veà laäp trình baèng ngoân ngöõ C

Phaâàn tröôùc | Muïc luïc | Phaâàn sau

XIII. Thao taùc vôùi chuoãi kyù töï (string)

Noäi dung:

Chuoãi kyù töï laø maûng kyù töï moät chieàu vôùi phaàn töû cuoái cuøng laø \0. Vôùi phaàn naøy ta laøm quen vôùi caùc haøm thao taùc vôùi chuoãi kyù töï:

 

Khai baùo chuoãi kyù töï

char  Array-Name[Array-Size];

char  Array-Name[];
char  *Array-Name;

Moät taäp hôïp kyù töï giôùi haïn bôûi caëp daáu ngoaêc keùp ñöôïc ngoân ngöõ C xem laø moät haèng chuoãi kyù töï (string constant). C seõ töï ñoäng theâm kyù töï (\0) vaøo cuoái daõy ñeå chæ keát thuùc cuûa chuoãi.

Ví duï: "A character string.", "Hello!" laø nhöõng haèng chuoãi kyù töï.

Ta coù theå gaùn giaù trò cho chuoãi kyù töï baèng nhöõng caùch sau:

char arr_str[7] = {`H', `e', `l', `l', `o', `!', `\0'};
 
char str[7] = "Hello!";
 
char str[] = "I like C.";
 
char *ptr_str = "I teach myself C.";
 

Chuù yù:

Khoâng neân khai baùo moät bieán chuoãi kyù töï maø kích thöôùc quaù nhoû so vôùi yù muoán chuùng ta söû duïng, vì neáu chuùng ta gaùn moät chuoãi daøi hôn bieán, coù theå gaây ra nhöõng loãi chöông trình khoâng ñònh tröôùc ñöôïc, maø boâ bieân dòch seõ khoâng baøo cho ta bieát. Ví duï:
char str[6] = "Hello!";
Laø moät pheùp gaùn sai (thieáu choã cho \0), nhöng boâ bieân dòch töï ñoäng caét ñi daáu ! maø khoâng baùo gì caû. 

Phaân bieät cuù phaùp phaân bieät giöõa kyù töï vaø chuoãi kyù töï:

char ch = `x'; /*1 byte*/
char str[] = "x"; /*2 bytes*/

Chuù yù khi chuoãi kyù töï ñöoïc bieåu dieãn döôùi daïng char pointer. Ta coù theå gaùn tröïc tieáp 1 chuoãi kyù töï cho moät bieán pointer:

char *ptr_str;
ptr_str = "A character string.";

Vaø khoâng theå ñöôïc:

ptr_str = `x';  /* Sai */

Phaûi söûa laïi nhö sau:

char *ptr_str;
*ptr_str = `x';

Ví duï:

1:  /* Initializing strings */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     char str1[] = {`A', ` `,
7:                    `s', `t', `r', `i', `n', `g', ` `,
8:                    `c', `o', `n', `s', `t', `a', `n', `t', `\0'};
9:     char str2[] = "Another string constant";
10:    char *ptr_str;
11:    int i;
12:
13:    /* print out str2 */
14:    for (i=0; str1[i]; i++)
15:       printf("%c", str1[i]);
16:    printf("\n");
17:    /* print out str2 */
18:    for (i=0; str2[i]; i++)
19:       printf("%c", str2[i]);

20:    printf("\n");
21:    /* assign a string to a pointer */
22:    ptr_str = "Assign a string to a pointer.";
23:    for (i=0; *ptr_str; i++)
24:       printf("%c", *ptr_str++);
25:    return 0;
26: }

Keát quaû:

A string constant
Another string constant
Assign a string to a pointer.

Chieàu daøi chuoãi kyù töï

Haøm strlen()

#include <string.h>
int strlen(const char *s);

s laø moät bieán con troû. Giaù trò traû laïi laø soá byte öùng vôùi ñoä daøi cuûa chuoãi kyù töï.

Ví duï:

1:  /* Measuring string length */
2:  #include <stdio.h>
3:  #include <string.h>
4:
5:  main()
6:  {
7:     char str1[] = {`A', ` `,
8:                    `s', `t', `r', `i', `n', `g', ` `,
9:                    `c', `o', `n', `s', `t', `a', `n', `t', `\0'};
10:    char str2[] = "Another string constant";
11:    char *ptr_str = "Assign a string to a pointer.";
12:
13:    printf("The length of str1 is: %d bytes\n", strlen(str1));
14:    printf("The length of str2 is: %d bytes\n", strlen(str2));
15:    printf("The length of the string assigned to ptr_str is: %d bytes\n",
16:       strlen(ptr_str));
17:    return 0;
18: }

Keát quaû:

The length of str1 is: 17 bytes
The length of str2 is: 23 bytes
The length of the string assigned to ptr_str is: 29 bytes

Sao cheùp chuoãi kyù töï

Haøm strcpy()

#include <string.h>
char *strcpy(char *dest, const char *src);

Noäi dung cuûa src seõ ñöôïc sao laïi cho dest. Haøm strcpy() seõ traû laïi giaù trò cuûa src neáu thao taùc thaønh coâng.

Ví duï:

1:  /* Copying strings */
2:  #include <stdio.h>
3:  #include <string.h>
4:
5:  main()
6:  {
7:     char str1[] = "Copy a string.";
8:     char str2[15];
9:     char str3[15];
10:    int  i;
11:
12:    /* with strcpy() */
13:    strcpy(str2, str1);
14:    /* without strcpy() */
15:    for (i=0; str1[i]; i++)
16:       str3[i] = str1[i];
17:    str3[i] = `\0';
18:    /* display str2 and str3 */
19:    printf("The content of str2: %s\n", str2);
20:    printf("The content of str3: %s\n", str3);
21:    return 0;
22: }

Keát quaû:

The content of str2: Copy a string.
The content of str3: Copy a string.

Ñoïc vaø ghi chuoãi kyù töï

Haøm gets() vaø puts()

Haøm gets() duøng ñeå ñoïc caùc kyù töï töø moät giao tieáp nhaäp chuaån (stdin).

#include <stdio.h>
char *gets(char *s);

Haøm gets() ñoïc caùc kyù töï gaùn vaøo bieán s cho ñeán ghi gaëp EOF vaø theâm vaøo \0. Neáu thaønh coâng, haøm traû laïi s; neáu khoâng seõ traû laïi con troû null.

Haøm puts() duøng ñeå xuaát caùc kyù töï cho moät giao tieáp xuaát chuaån (stdout).

#include <stdio.h>
int puts(const char *s);

Neáu thao taùc thaønh coâng, haøm traû laïi giaù trò 0; neáu khoâng seõ traû laïi giaù trò khaùc 0. Haøm puts() seõ theâm EOF thay cho kyù töï \0.

Ví duï:

1:  /* Using gets() and puts() */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     char str[80];
7:     int i, delt = `a' - `A';
8:
9:     printf("Enter a string less than 80 characters:\n");
10:    gets( str );
11:    i = 0;
12:    while (str[i]){
13:      if ((str[i] >= `a') && (str[i] <= `z'))
14:         str[i] -= delt;  /* convert to upper case */
15:      ++i;
16:    }
17:    printf("The entered string is (in uppercase):\n");
18:    puts( str );

19:    return 0;
20: }

Keát quaû:

Enter a string less than 80 characters:
This is a test.
The entered string is (in uppercase):
THIS IS A TEST.

Coù theå söû duïng %s trong haøm printf() ñeå xuaát moät chuoãi kyù töï ra maøn aûnh.

Haøm scanf()

Coù theå söû duïng haøm scanf() ñeå ñoïc kyù töï töø giao tieáp nhaäp chuaån, vôùi format töông töï nhö printf().

#include <stdio.h>
int scanf(const char *format, …);

Neáu thao taùc thaønh coâng, haøm traû laïi soá döõ lieäu ñoïc töø stdin; neáu khoâng seõ traû laïi EOF.

Ví duï:

1:  /* Using scanf() */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     char str[80];
7:     int x, y;
8:     float z;
9:
10:    printf("Enter two integers separated by a space:\n");
11:    scanf("%d  %d", &x, &y);
12:    printf("Enter a floating-point number:\n");
13:    scanf("%f", &z);
14:    printf("Enter a string:\n");
15:    scanf("%s", str);
16:    printf("Here are what you've entered:\n");

17:    printf("%d  %d\n%f\n%s\n", x, y, z, str);
18:    return 0;
19: }

Keát quaû:

Enter two integers separated by a space:
10  12345
Enter a floating-point number:
1.234567
Enter a string:
Test
Here are what you've entered:
10  12345
1.234567
Test

Baøi taäp

  1. Bieåu thöùc naøo sau ñaây ñuùng?
  2. Cho bieán con troû ptr_ch, Bieåu thöùc naøo sau ñaây ñuùng?
  3. Vieát moät chöông trình tính ñoä daøi cuûa moät chuoãi kyù töï baèng caùch ñeám töøng kyù töï. Sau ñoù duøng haøm strlen() ñeå so saùnh.
  4. Vieát chöông trình söû duïng scanf() ñeå ñoïc 2 soá nguyeân do ngöôøi söû duïng cho vaøo, coäng 2 soá ñoù vaø in toång leân maøn aûnh.

Phaâàn tröôùc | Muïc luïc | Phaâàn sau