Implementing ‘strlen( )’ using command line arguments

IMPLEMENTATION OF STANDARD STRING LIBRARY FUNCTIONS USING COMMAND LINE ARGUMENTS

Command line arguments:

In C language main() is the only function which can defined in multiple ways.It can recieve no arguments, two arguments or 3 arguments. Using these arguments the main function will recieve the arguments from the console.
The main function can be define in the following ways:
1. int main( )
2. int main( int argc, char *argv[ ])

argc:
It is called as argument count ,it tells the number of arguments that is being passed to the main function.

argv[ ]:
This is called as argument vector ,its an array whose each element would be pointing to the arguments that are passed to the main function.

Implementing strlen( ):

strlen( ) is a standard library function which is used to find total number of characters in a string excluding ‘\0’ character.

Example :

 

We are taking the input from the user using command line arguments.
input = $ ./a.out Subhash Shubha Vidya Prajna
output :
Subhash = 7
Shubha = 6
Vidya = 5
Prajna = 6 (i.e. total Number of characters in each string)

In the above example “Subhash” is the string which contains 7 characters and it is recieved through the command line arguments. So argv[1] = “Subhash” .

The strlen( ) calculates the total number of characters in the argv[1] ,in this case it gives output as 7.

Logic:

 

1. Take the string through the command line argument.
2. Consider a variable ‘i’ and initialise it into ‘0’.
3. Call the function my_strlen( ) and pass the base address of the argv[i] until i is equal to (argc – 1) .
4. The control goes to the function defination( void my_strlen(char * s)).
5. Initialize count = 0 and increment the count until the character to which the pointer s is pointing encounters ‘\0’ .

Source code:

#include<stdio.h>
void my_strlen(char*)
int main(int arc, char*argv[ ] )
{
          int i;
         for(i = 0; i< argc ; i++); 
         {
                     my_strlen(argv[i]);
         }
}
void my_strlen(char *s)
{
          int count;
          for(count = 0; *s != '\0'; s++)
         {
                   count ++;
       }
       printf("The string length of %s = %d\n", s ,count);
}

 

This article is written by one of my student as part of their blog writing exercise.

To learn more programs on C and C++, click this link: Interview Questions

Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.

VIEW SUBHASH’s PROFILE

SUBHASH LOVES TO TEACH ! CLICK HERE !

Subhash Embedded Classes is one of the Best Embedded Systems Training Institute in Bangalore

No Comment

You can post first response comment.

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.