C Program to Find Length of the String using Pointer
Program to Calculate Length of the String using Pointer
Write a C Program which will accept string from the user . Pass this string to the function. Calculate the length of the string using pointer.
Program : Length of the String using Pointer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include<stdio.h> #include<conio.h> int string_ln(char*); void main() { char str[20]; int length; clrscr(); printf("\nEnter any string : "); gets(str); length = string_ln(str); printf("The length of the given string %s is : %d", str, length); getch(); } int string_ln(char*p) /* p=&str[0] */ { int count = 0; while (*p != '\0') { count++; p++; } return count; } |
Output :
1 2 | Enter the String : pritesh Length of the given string pritesh is : 7 |
Explanation :
- gets() is used to accept string with spaces.
- we are passing accepted string to the function.
- Inside function we have stored this string in pointer. (i.e base of the string is stored inside pointer variable).
- Inside while loop we are going to count single letter and incrementing pointer further till we get null character.