Home › Forums › Programming › C Program to find length of string without using Library function
Tagged: c, functions, sting, string lenght
- This topic has 1 reply, 2 voices, and was last updated 13 years, 3 months ago by Satish.
- AuthorPosts
- January 16, 2012 at 5:30 am#1136BasavarajMember
- #include<stdio.h>
- #include<conio.h>
- void main()
- {
- int length( char *p ); // Function prototype.
- char *ptr; // char pointer to read the string.
- int len; // variable in which length is stored.
- clrscr();
- printf("Enter a string : ");
- gets( ptr ); // reading string from keyboard
- len=length( ptr ); // string is passed as argument to function( funcation call)
- printf("Length of string is : %d",len); // displaying the result.
- getch();
- }
- int length( char *p ) // Function definition
- {
- int len=0;
- while( *p )
- {
- len++;
- p++;
- }
- return(len);
- }
#include<stdio.h> #include<conio.h> void main() { int length( char *p ); // Function prototype. char *ptr; // char pointer to read the string. int len; // variable in which length is stored. clrscr(); printf("Enter a string : "); gets( ptr ); // reading string from keyboard len=length( ptr ); // string is passed as argument to function( funcation call) printf("Length of string is : %d",len); // displaying the result. getch(); } int length( char *p ) // Function definition { int len=0; while( *p ) { len++; p++; } return(len); }
This problem is solved by defining out own function to find the length of string. here i have used char pointer to read the string.
using the concept of pointer we could solve the problem easily.the while loop while( *P ) { len++; } gets executed repeatedly until it encounters null char which is usually present at the end of the string. the *p is written to fetch char from its pointer it is known as indirection operator,after fetching the char the pointer is incremented using the statement p++ which will make the pointer to point to the next char.
January 16, 2012 at 5:49 am#1140SatishKeymasterSir, edit the post and use these syntax to format it to look better.
don’t forget about the < and > replacement strings of html while writing the code.
- AuthorPosts
- You must be logged in to reply to this topic.