This program prints length of string, for example consider the string "c programming" it's length is 13. Null character is not counted when calculating string length. To find string length we use strlen function of string.h.
C program to find string length
#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int length;
printf("Enter a string to calculate it's length\n");
gets(a);
length = strlen(a);
printf("Length of entered string is = %d\n",length);
return 0;
}
Output of program:
C program to find string length without strlen
You can also find string length without strlen function. We create our own function to find string length.
#include <stdio.h>
int string_length(char []);
int main()
{
char s[1000];
int length;
printf("Input a string\n");
gets(s);
length = string_length(s);
printf("Length of \"%s\" = %d\n", s, length);
return 0;
}
int string_length(char s[]) {
int c = 0;
while (s[c] != '\0')
c++;
return c;
}
Function to find string length using pointers
int string_length(char *s) {
int c = 0;
while(*(s+c))
c++;
return c;
}
No comments:
Post a Comment