Search C Program | nimishsoft@gmail.com

String Length - STRLEN

/* STRING LENGTH - STRLEN*/
 
#include<stdio.h>

int main()
{
 char str[100];
 int i;
 printf("Please enter a string: ");

 // gets(str); 
 // fgets is a better option over gets to read multiword string .

 fgets(str, 100, stdin);

 // Following can be added for extra precaution for '\n' character
 // if(str[length(str)-1] == '\n') str[strlen(str)-1]=NULL;

 for(i=0;str[i]!=NULL;i++);
 
 printf("Length of string is: %d",i);

 return 0;
}
 

3 comments:

  1. Change in the printf statement :-
    printf("Length of string is: %d",--i);

    ReplyDelete
    Replies
    1. No need to decrement the i, because it starts at 0.

      Delete
  2. #include
    #include
    #include
    void main()
    {
    char str[100];
    int n;
    clrscr();
    gets(str);
    n=strlen(str);
    printf("length is %d",n);
    getch();
    }

    ReplyDelete