Skip to main content

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 array is equivalent to the base address of the array.

name is equivalent to &name[0]


Let us now look at the function definition.
int xstrlen(char *a)
{
    int length = 0;
    while(*a!='\0')
    {
      length++;
      a++;
    }
    return length;
}
Here we are using the fact that a string always terminates with a null character '\0'  .So we just looped through the value at the memory address 

The output is:

The length of the string is 8

xstrcpy

As the name suggest xstrcpy is a function which acts similar as strcpy function,which copies one string to another.
#include<stdio.h>
void xstrcpy(char* ,char* );

int main()
{
  char name[]="Abhilekh";
  char copyName[8];
  xstrcpy(copyName,name);
  printf("copyName is %s",copyName);
  return 0;
}
void xstrcpy(char *a, char *b)
{
    int length=0;
    while(*b!='\0')
    {
        *= *b;
        a++;
        b++;
    }
    *= '\0';
}

Let us look at the function prototype first.

void xstrcpy(char *,char*);

The function is expecting two char
pointers.

The function call is:
xstrcpy(copyName,name);

The function definition is:
void xstrcpy(char *a, char *b)
{
    int length=0;
    while(*b!='\0')
    {
        *= *b;
        a++;
        b++;
    }
    *= '\0';
}

We run the loop until the value at the
string is equal to the null character
and assigned the value at one string
to another until the loop condition
fails.

The output is:

copyName is Abhilekh


xstrcmp

As the name suggest xstrcmp is a function which works similar as strcmp function,It compares two strings and returns the ASCII difference between those strings.
#include<stdio.h>
int xstrcmp(char *,char *);

int main()
{
 if(xstrcmp("Kathmandu","Kathman")==0)
  printf("Both the strings are same");

  else
   {
    printf("They are different");
   }
  return 0;
}

int xstrcmp(char *a ,char *b)
{
    int diff;
    int counter;
    int lengtha = 0;
    int lengthb = 0;
    while(*!='\0')
    {
        lengtha++;
        a++;
    }
    while(*!='\0')
    {
        lengthb++;
        b++;
    }
counter=lengtha>lengthb?lengtha:lengthb;
    for(int i = 0 ; i< counter ; i++)
    {
        if(a[i]==b[i])
        {
            diff = 0;
            continue;
        }
        else
        {
            diff = a[i- b[i];
           return diff;
        }
    }
    return diff;
}

Similar to above function the function expects two char pointer as its Parameter and returns the difference between the character of the array.

xstrcat

As the name suggest xstrcat is a function which works similar as strcat function, It joins(concatenates) two strings.
#include<stdio.h>
void xstrcat(char *,char*);

int main()
{
  char str1[10]="Abhilekh";
  char str2[20]= "Gautam";

  xstrcat(str2,str1);
  printf("Concatinated form is %s",str2);
}
void xstrcat(char *a,char*b)
{
   while(*a!='\0')
   {
       a++;
   }
   while(*!= '\0')
   {
       *= *b;
       b++;
       a++;
   }
   *= '\0';
   
}


The output is:

Concatinated form is GautamAbhilekh

xstrlwr

As the name suggest xstrlwr is a function which works similar as strlwr function, It converts a string into lowercase.
#include<stdio.h>
void xstrlwr(char *);

int main()
{
    char name[]="ABHILEKH";
    xstrlwr(name);
    printf("Name:%s",name);
    return 0;
}

void xstrlwr(char *a)
{
    int i=0;
    while(*a!='\0')
    {
        if(*a>=65 && *a<=90)
        {
            *= *+ 32;
        }
        i++;
        a++;
    }

We use the fact that when a uppercase alphabetical character is added with 32 gives the corresponding lowercase alphabetical character.

The output is:

Name:abhilekh

xstrupr

As the name suggest xstrupr is a function which works similar as strupr function, It converts a string into uppercase.
#include<stdio.h>
void xstrupr(char *);

int main()
{
    char name[]="Abhilekh";
    xstrupr(name);
    printf("Name:%s",name);
    return 0;
}

void xstrupr(char *a)
{
    int i=0;
    while(*a!='\0')
    {
        if(*a>=97 && *a<=122)
        {
            *= *- 32;
        }
        i++;
        a++;
    }
}

We use the fact that when a lowercase alphabetical character is subtracted with 32 gives the corresponding uppercase alphabetical character.


The output is:

Name:ABHILEKH


xstrrev

As the name suggest xstrrev is a function which works similar as strrev function, It reverses a string.
#include<stdio.h>
char * xstrrev(char *);

int main()
{
 char name[]="Abhilekh";
 printf("Reverse is %s",xstrrev(name));
  return 0;

}

char * xstrrev(char *a)
{
     int i,j;
    char name[8];
    for(i = 0 ; a[i]!='\0';i++)
    {
        name[i]= a[i];
    }
    name[i= '\0';
   
 for(i = 0,j=7;name[i]!='\0';i++,j--)
  {
   a[i= name[j];
  }
  a[i= '\0';
  return a;  
}

Here the function prototype is 

char* xstrrev(char *);

The function returns a character
pointer.

The output is:


The reversed form is hkelihbA

All the above codes are available in this git repo as well.

That's It!

Happy Coding


Comments

Popular posts from this blog

What is this Pointer in C++?

 Pointers are always headache for Programmers. However C++ have a special pointer which is referred as ' this '. The this pointer is one of the important concept in C++ and can be really confusing too. So in this article I will be discussing about the this pointer and its role in C++. The this Pointer Let us see an example first. # include < iostream > using   namespace  std; class   A { int   a ; public: // constructor A ( int   x   =   0 ): a ( x ){} void   display ()  const {      cout << a << ' \n ' ; } }; int   main (){ A   objA ( 10 ); A   objB ( 11 ); objA . display (); objB . display (); return   0 ; } It is very clear that the output will be 10 11 The program looks very simple, But do you know whats going on, under the Hood? How does the function remember, which object is invoking it? This is where the this pointer comes in action. Actually, the Compiler is secretly passing a constant pointer pointing to the object

File Handling and Various File Opening Modes in C

Every programs we were doing before were using Memory for storage and all those memory would wipe out once the program is terminated.But sometime the case is different,what if we need all those data again,We need to re-enter all those bulky data again,which will again be wiped out once the program is terminated. So we need to store the data in such a place such that it can be retrieved and displayed again and again.This is why we need files.The place about which we previously talked is the file on the disk.So we need File Handling to work with files. Let us see how a file can be handled. Various Operations in Files Creating a File Opening a File Reading from a File Writing to a File Closing a File File Opening Modes in C Before performing any operations in files,we must create/open the file . Here are the various File opening modes in C. "r" : It searches the file.If the file opens up successfully,the function fopen() loads the file from disk to memory and sets a pointer

What is Storage class and What are their types in C

 Variable declaration is not complete until we mention its storage class( there are some default conditions as well). Yeah you got it right ,Variables not only have data types they have storage class too. Why storage class? They tell us about The scope of the variable. Life time of the variable. Initial value of the the variable, if left unassigned. We have four storage class in C Automatic storage class External storage class Static storage class Register storage class Let us look at them one by one. Automatic Storage Class Scope : Local to the block where it is defined. Life Time : Until the control remains in the block. Initial value : A garbage value, one cannot predict. We use the keyword auto to declare a variable of automatic storage class. Demonstration of  Automatic storage class # include < stdio.h > void   myFunc (); int   main () {     auto  int   x   =   5 ;      printf ( " %d " , x ) ;      myFunc () ;      return   0 ; } void   myFunc () { int x;  

What is Structure and why do we need them in C

 In one of our previous post we dealt with Array .Here in this post we'll be dealing with structure which  I prefer to call 'The advanced version of arrays'. Structure Similar to an array, A structure is a collection, however of a dissimilar data types. Take an example of an office, Where the Manager wants to keep  the records of his/her employees.The record may include employees' name, address, department, pay scale , age and so on.So, why not create a variable with all those features in it. So when we want an entity with multiple features in it we can go with structures. First Glance of Structure struct   student {      int   rollNo , intake Year;      char   name [ 20 ], address [ 20 ]; }; Above is a structure student with some of the features of the student like:Roll number, intake year, their name and address. The keyword struct is used to define a structure. Structure definition always ends with a semicolon. The general form of Structure definition is struct   <

Arrays and static Memory allocation in C

In this post we will be talking about array, their usage and importance in C. Array Array in simple world is a collection/container of elements of  same type. Array of any type is possible but the elements in array cannot be of multiple types. We can have array of int type. But not a array with 5 element of int and other element of other types . Why Array? Imagine a problem where you want to input the marks of 10 student in a subject  from the user and display the marks in descending number. Our major problem above will be to store the number input by the user. Here we have two options : Either construct 10 variables for storing marks of 10 student .(A trash Idea) Or Construct a container (Array of integers in this case) which can store all the marks of student . First Glance of an Array As mentioned earlier array is a nothing else than a collection for us. int   marks [ 10 ]  =  { ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' }; This is what an array lo

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

What is Operator Overloading in c++

  Who doesnot love syntactic sugar ? After all they make our code look more beautiful. So let us discuss how to  overload operators in C++ How to Overload Operators in C++ What if I tell you ,You can use most of the operator in C++ not only with built in type but with the  type you defined yourself (Classes are user defined type) .Yes you got it right , operator overloading lets you define the meaning of  an operator when used to operands of user defined type(classes) Overloaded operator are nothing else than a function (however a special one) with a special keyword operator followed by the symbol for the operator to be overloaded. As I already mentioned that overloaded opeartors are a function so they definetly have a return type,parameter(s) and a body. It should look something like this: returnType operator Symbol(){} As an example:   int   operator  +(){ // body } Let us now overload   plus operator (+) for our class . 1.# include < iostream > 2.using   namespace  std; 3. 4

What is Dynamic Memory Allocation in C

Under stdlib header C provides us 4 four special function which helps in allocating memory dynamically and freeing it. malloc() calloc() realloc() free() The first three function's are used in allocation of memory while the last one frees the allocated memory. The Malloc function Syntax malloc ( number_of_bytes ); The malloc function  allocates contiguous memory location for the required   number_of_bytes, returns a void pointer pointing to the base address of that allocated memory. A malloc returns a void pointer,why?because malloc does not know for what we allocated the memory ( malloc does not know whether we are allocating memory for ints , floats or chars ). Usage example int   * a = ( int * )  malloc (5 *sizeof ( int )); The (int*) is done for typecasting, it converts the void pointer returned by malloc function to a integer pointer (int*) . We are then assigning the returned(and type casted) pointer to a integer point a. So a is now pointing to the base address of allocated