String declaration and initialization

String declaration: There is no string data type in c. So string is declared as the array of characters.

Syntax:            char variable-name[size];

e.g:      char S[10];

String initialization: like the integer array the character array can also initialized at the time of declaration.  The two following methods are for string initialization.

  1. char name[13]=”jatin sharma”;
  2. char name[13]={’j’,’a’,’t’,’i’,’n’,’ ’,’s’,’h’,’a’,’r’,’m’,’a’,’\0’};

we have used 13 size for the string because in the last the compiler automatically inserts the ‘\0’ which called null character. And remember ‘ ’ space is also a character.

Run time initialization: we have many functions to initialize the string at run time. These are:

scanf(): scanf() function is also used for the other data types and it used ‘%s’ in the function.

Syntax:            scanf(“%s”,variable-name);

e.g:      scanf(“%s”,str);

getchar(): getchar() function is used for read only one character.

Syntax:            variable=getchar();

e.g:      char a;

a=getchar();

gets(): gets() function is used for input a line of string.

Syntax:            char variable-name[size];

gets(variable);

e.g:      char str[20];

gets(str);

Posted in C

Leave a Reply

Your email address will not be published. Required fields are marked *