This blog is under construction

Sunday 21 July 2013

C program to find length of a string using pointers

Write a C program to find length of a string using pointers.


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

  int main() {
        char str[256];
        int i, len = 0;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(str, 256, stdin);

        /* calculate the length of the given string */
        for (i = 0; (str[i] != '\n' && str[i] != '\0'); i++) {
                len++;
        }

        /* prints the length of the given string */
        printf("Length of the given string is %d\n", len);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:hello world
  Length of the given string is 11


No comments:

Post a Comment