Thursday, September 10, 2020

C program to seek out the length of the string with or without using strlen function in c


 Here we'll write a C program to seek out the length of the string. The length of the "Computerinhindi" string is 15.

C program to seek out the length of the string with or without using strlen function in c
C program to seek out the length of the string with or without using strlen function in c
Find string length without using string library functions in C programming

To find the length, use for loop or while loop. The program below uses the for loop to check the string length in c program.

#include
int main()
{
     char st[200];
     int i;

     printf("Enter a string: ");
     scanf("%[^\n]",str);

     for(i=0;st[i]!='\0';i++);

     printf("length of given string is=%d",i);

     return 0;
}

The variable i is initialized with 0 inside the for loop. Now the condition str [i]! = '\ 0' are going to be checked for every character within the string. When the condition is true, the worth of the variable i will be able to increment.  


At the top of the string, it encounters a null character ("\ 0") therefore the condition becomes false and therefore the value of the variable i will be able to not increment, loop terminated. Finally, we get the length of the string without employing a built-in strlen () function in C program.

C Program to check String length using strlen()

  •  The strlen () function returns the length of the string passed.
  •  strlen () doesn't count the null character "\ 0"
  •  the specified header file may be a string.
#include
#include
int main()
{
     char a[20]="Computerinhindi";
     char b[20]={'C','O','R','N','N','E','R','\0'};
     char c[20];

     printf("Enter a string: ");
     scanf("%[^\n]",c);

     printf("Length of given string in c program %s =%ld\n",a,strlen(a));
     printf("Length of given string %s =%ld\n",b,strlen(b));
     printf("Length of string in c program %s =%ld\n",c,strlen(c));

     return 0;
 }

Here is that the C program to seek out the length of the string, to require user input we will use gets () or fgets (). The fgets () function also returns the newline character to the string. 

If you employ the fgets () function as shown below, you'll get result = (actual length + 1). The gets () takes an equivalent input length as [^ \ n] took. For an equivalent string, gets () gives the length 14 except for fgets () gives the length 15.

0 comments:

Post a Comment