C strlen

  • strlen( ) function counts the number of characters in a given string and returns the integer value.
  • It stops counting the character when null character is found. Because, null character indicates the end of the string in C.

 Syntax of strlen()

strlen(argument);


It is defined in the <string.h> header file.

The following program calculates the length of the string entered by the user.

#include<stdio.h>
#include<string.h>

int main()
{
    int len;

    // destination array can store only 30 characters including '\0'
    char destination[30];

    printf("Enter your dream destination: ");
    gets(destination);

    // calculate length of characters in destination
    len = strlen(destination); 

    printf("Your dream destination %s has %d characters in it", destination, len);

    return 0;
}

 Output:

 

 

Calculate Length of String without Using strlen() Function
 
#include<stdio.h>
 
int main() {
   char str[100];
   int length;
 
   printf("\nEnter the String : ");
   gets(str);
 
   length = 0;  // Initial Length
 
   while (str[length] != '\0')
      length++;
 
   printf("\nLength of the String is : %d", length);
   return(0);
}
 
Output
 

 

No comments:

Post a Comment