Tuesday, November 11, 2014

4.1.5 CHARACTER ARRAYS / STRINGS


A string is a sequence of characters that is treated as a single data item.

 

Declaring and Initializing String Variables

·         C does not support strings as a data type.

·         C, however, allows us to represent strings as character arrays.

 

General form:

   char string_name[size];

 

The ‘size’ determines the number of characters in the string_name.

e.g. char city[10];

        char name[30];

 

when the compiler assigns a character string to a character array, it automatically supplies a null character(\’0’) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one.

 

Initialization

     char city[9] = “NEW YORK”;

     char city[9] = {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};

 

·         C also permits us to initialize a character array without specifying the number of elements. In such cases, the size of the array will be determined automatically, based on the number of elements initialized.

e.g.  char city[ ] = {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};

 

·         We can also declare the size much larger than the string size in the initialize.

e.g. char str[10] = “GOOD”;

 

G
O
O
D
\0
\0
\0
\0
\0
\0

 

 

Reading Strings from Terminal

1.      Using scanf() Function

char address[10];

scanf(“%s”,address);

            Here, scanf() is used with %s format specification to read a string of characters.

           

NOTE: that unlike previous scanf calls, in the case of character arrays, the ampersand (&) is not required before the variable name.

·         The problem with the scanf( ) function is that it terminates its input on the first white space it finds.


Reading a Line of Text
C supports a format specification known as the edit set conversion code%[ ] that can be used to read a line containing a variety of characters, including whitespaces.
e.g.    char line[80];
          scanf(“%[\n]”,line);
          printf(“%s”, line);
The above program segment reads a line of input from the keyboard and display the same on the screen.
 

 

 

 

 


2.      Using getchar() and gets() Functions

a.      getchar()

This function is used to repeatedly read successive single characters from the input and place them into a character array.

            An entire line of text can be read and stored in an array. The reading is terminated when the newline character(‘\n’) is entered and the null character is then inserted at the end of the string.

General format:

               char ch;

   ch = getchar();

                       

                        Code Segment:

                                    char line[80],ch;

                                    int c = 0;

                                    printf(“Enter text:”);

                                    do

                                    {

                                                ch=getchar();

                                                line[c] = ch;

                                                c++;

                                    } while(ch !=’\n’);

 

b.      gets()

This function is available in the <stdio.h> header file.

General format:

               gets(str);

   where str is a string name.

This function reads characters into the character array from the keyboard until a new-line character is encountered and then adds a null character to the string.

                       

                        Code Segment:

                                    char line[80];

                                    gets(line);

 

Writing Strings to Screen

1.      Using printf() Function

The format %s can be used to display an array of characters that is terminated by the null character.

                        printf(“%s”,name);

 

2.      Using putchar() and puts() Functions

a.      putchar()

C supports another character handling function putchar() to output the values of character variables. It takes the following form:

            char ch = ‘A’;

            putchar(ch);

 

Code Segment:

                                    char name[6] = “ARNAV’;

                                    for(i=0; i<6; i++)

                                          putchar(name[i]);

 

b.      puts()

The function puts() is defined in the header file <stdio.h>.

General format:

               puts(str);

   where str is a string name.

                       

                        Code Segment:

                                    char line[80];

                                    gets(line);

                                    puts(line);

 

All the string handling functions are prototyped in:

#include <string.h>

 
The common functions are described below:

1.      strcpy

This library function is used to copy a string and can be used like this:

strcpy(destination, source)

 (It is not possible in C to do this: string1 = string2).

Take a look at the following example:

 
               str_one = "abc";
               str_two = "def";
               strcpy(str_one , str_two); // str_one becomes "def"

Note: strcpy() will not perform any boundary checking, and thus there is a risk of overrunning the strings.

2.      strcmp

This library function is used to compare two strings and can be used like this:

strcmp(str1, str2)

  • If the first string is greater than the second string a number greater than null is returned.
  • If the first string is less than the second string a number less than null is returned.
  • If the first and the second string are equal a null is returned.

Take look at an example:

               printf("Enter you name: ");
               scanf("%s", name);
               if( strcmp( name, "jane" ) == 0 )
                               printf("Hello, jane!\n");
 
Note: strcmp() will not perform any boundary checking, and thus there is a risk of overrunning the string.

 


3.      strcat

This library function concatenates a string onto the end of the other string. The result is returned. Take a look at the example:

               printf("Enter you age: ");
               scanf("%s", age);
               result = strcat( age, " years old." ) == 0 )
               printf("You are %s\n", result);
 
Note: strcat() will not perform any boundary checking, and thus there is a risk of overrunning the strings.

 

4.      strlen

This library function returns the length of a string. (All characters before the null termination.) Take a look at the example:

 
               name = "jane";
               result = strlen(name); //Will return size of four.
 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.