Skip to main content

Posts

Showing posts with the label strings

Making your own version of string handling function in C

 In the previous post we discussed about  string handling functions in C . In this post we'll be defining our own version for those function. Let's see how. xstrlen As the name suggests xstrlen will be function performing same functions as strlen function which returns the length of the string. # include < stdio.h > int   xstrlen ( char   * ); int   main () { char   name [] = " Abhilekh " ; printf ( " length is  %d " , xstrlen ( name )) ; return   0 ; } int   xstrlen ( char   * a) {      int   length   =   0 ;      while ( * a != ' \0 ' )     {        length ++ ;       a ++ ;     }      return   length ; } Look at the function prototype. int   xstrlen ( char   * ); It is very clear that the function is expecting a character pointer as a parameter and the function will be returning a integer value. Let us now see how we are calling the function, xstrlen ( name ) We are passing the name_of_array as a parameter. It should be noted that the name of

Working with String Handling Functions in C

 C provides large set of string handling library function under string.h header. Few of them are discussed below. Strlen This function returns the length of the given string which is an integer value. Syntax strlen (name_of_array); The actual parameter for the function is the address of the first character of the array. Usage # include < stdio.h > # include < string.h > int   main () { char   name [] = " Abhilekh " ; printf ( " length is  %d " , strlen ( name )) ; return   0 ; } The output is: The  length  of the string is  8 Strcpy It should be noted that a string cannot be assigned to another string using a assignment operator(=). This is where we use this library function. It copies one string to another. Syntax strcpy (string1,string2); It copies the string from string2 to string1. Usage # include < stdio.h > # include < string.h > int   main () {   char   name [] = " Abhilekh " ;   char   copyName [ 8 ];   strcpy ( copyName , n