Strings in c

The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array. Character arrays are many a time also called strings. Many languages internally treat strings as character arrays

A string constant is a one-dimensional array of characters terminated by a null ( ‘\0’ )

char name[ ] = { ‘H’, ‘A’, ‘E’, ‘S’, ‘L’, ‘E’, ‘R’, ‘\0’ } ;

Each character in the array occupies one byte of memory and the last character is always ‘\0’. What character is this? It looks like two characters, but it is actually only one character, with the \ indicating that what follows it is something special. ‘\0’ is called null character. Note that ‘\0’ and ‘0’ are not same

The terminating null (‘\0’) is important, because it is the only way the functions that work with a string can know where the string ends. In fact, a string not terminated by a ‘\0’ is not really a string, but merely a collection of characters.

Program to demonstrate printing of a string

main( ) 
{ 
char name[ ] = "Klinsman" ; 
int i = 0 ; 
while ( i <= 7 ) 
 { 
printf ( "%c", name[i] ) ; 
 i++ ; 
 }
}

Output

Klinsman

In other way

main( ) 
{ 
 char name[ ] = "Klinsman" ; 
 int i = 0 ; 
 while ( name[i] != `\0' ) 
 { 
 printf ( "%c", name[i] ) ; 
 i++ ; 
 } 
}

using pointer

main( ) 
{ 
 char name[ ] = "Klinsman" ; 
 char *ptr ;
ptr = name ; /* store base address of string */ 
 while ( *ptr != `\0' ) 
 { 
 printf ( "%c", *ptr ) ; 
 ptr++ ; 
 } 
} 

The %s used in printf( ) is a format specification for printing out a string. The same specification can be used to receive a string from the keyboard

main( )
{
char name[25] ;
printf ( “Enter your name ” ) ;
scanf ( “%s”, name ) ;
printf ( “Hello %s!”, name ) ;
}

scanf( ) is not capable of receiving multi-word strings. Therefore names such as ‘Debashish Roy’ would be unacceptable. The way to get around this limitation is by using the function gets( ). The usage of functions gets( ) and its counterpart puts( )

main( )
{
char name[25] ;
printf ( “Enter your full name ” ) ;
gets ( name ) ;
puts ( “Hello!” ) ;
puts ( name ) ;
}

Output

Enter your name Debashish Roy
Hello!
Debashish Roy

Leave a Comment