Wednesday, November 2, 2011

strlen( ) in C programming language

This function counts the number of characters present in a string. Its usage is illustrated in the following program.

main( )
{
      char  arr[ ] = "Bamboozled" ;
      int  len1, len2 ;
      len1 = strlen ( arr ) ;
      len2 = strlen ( "Humpty Dumpty" ) ;

      printf ( "\nstring = %s length = %d", arr, len1 ) ;
      printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
}

The output would be...

string = Bamboozled length = 10
string = Humpty Dumpty length = 13

Note that in the first call to the function strlen( ), we are passing the base address of the string, and the function in turn returns the length of the string. While calculating the length it doesn’t count ‘\0’. Even in the second call,

len2 = strlen ( "Humpty Dumpty" ) ;

what gets passed to strlen( ) is the address of the string and not the string itself. Can we not write a function xstrlen( ) which imitates the standard library function strlen( )? Let us give it a try...

/* A look-alike of the function strlen( ) */ 
main( )
{
      char  arr[ ] = "Bamboozled" ;
      int  len1, len2 ;

      len1 = xstrlen ( arr ) ;
      len2 = xstrlen ( "Humpty Dumpty" ) ;

      printf ( "\nstring = %s length = %d", arr, len1 ) ;
      printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
}
xstrlen ( char  *s )
{
      int  length = 0 ;

      while ( *s != '\0' )
 {
  length++ ;
  s++ ;
 }

      return ( length ) ;


The output would be...

string = Bamboozled length = 10
string = Humpty Dumpty length = 13

The function xstrlen( ) is fairly simple. All that it does is keep counting the characters till the end of string is not met. Or in other words keep counting characters till the pointer s doesn’t point to ‘\0’.

No comments:

Post a Comment