strings definition, declaration, initilization - C-Tutorial

Latest

Friday, 7 October 2016

strings definition, declaration, initilization

STRINGS


  • ·         A string is collection of "characters" (or) "array of characters"
  • ·         C Strings are nothing but array of characters ended with null character (‘\0’).
  • ·         This null character indicates the end of the string.
  • ·         Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.

 Declaration:

Syntax                        :           char StringName [size];
Example         :           char str[100];

  The general format of initializing a string is:

Syntax             :           char stringname[size] = “string value”;
           
  •             Here, collection of characters is placed within double quotation marks and termed as string constant.


                        Example          :           char str[50] = “Language in 1972”;

  •  Strings can also be initialized in the form of character array.  In such cases, explicitly it is necessary to add the NULL character (‘\0’) at the end of the string value.

           
                        Syntax      :     char stringname[size] = { ‘value1’ , ‘value2’, … , ‘\0’};

                        Example   :     char str[10] = {‘H’ , ‘E’ , ‘L’ , ‘L’ , ‘O’ , ‘\0’};

STRING INPUT/OUTPUT FUNCTIONS

These gets() and puts() functions are used for reading and print an entire line as a string including blank spaces.  These library functions information is available in stdio.h header file.

gets() function:    gets() function used for reading an entire line as a string including blank spaces.  

            Syntax             :           gets(string);


puts() function:          puts() function used for printing an entire line as a string including blank spaces.  

            Syntax             :           puts(string);
           

/* EXAMPLE PROGRAM FOR READING AND PRINT A STRING */

#include<stdio.h>
#include<conio.h>

main()
{
            char str[50];
            clrscr();
            printf("\nEnter a line of text:");
            gets(str);
            printf("\n RESULT1:");
            puts(str);

}

No comments:

Post a Comment