Question

Write a function that can return the length of a string in C language. Please leave...

Write a function that can return the length of a string in C language. Please leave comments to explain the code and verify that it runs properly...

Example:

Input String: China

The length of the string is 5.

#include <stdio.h>

int length(char * p)

{

    /write your code here

}

main(){

    int len;

    char str[20];

    printf("Input string:");

    scanf("%s", str);

    len = length(str);

    printf("The length of string is %d. ", len);

    getchar();

    getchar();

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The following is the C code:

// this is a program to calculate the length of a string

#include <stdio.h>

int length(char *p)
{
   int len = 0; // len is the current length of the string
   while (p[len] != '\0') // every string ends with a null character
   {
       len++; // if null character wasn't seen then incremement length by 1
   }
   return len;
}

int main() // this is the main method
{
   int len;
   char str[20];
   printf("Input String: "); // take an input string
   scanf ("%s", str);
   len = length (str); // find the length of the string using the function created above
   printf("The length is %d.\n", len); // print the length of the string
   getchar();
   getchar();
   return 0;
}

---------------------------------------------

The following is the screenshot of the output:

lengthofstr$ gcc los.c lengthofstrs ./a.out Input String: Helloworld The length is 10

----------------------------------------------

In the code segment, provided by you scanf has been used to take the input from the user. So, I've kept it as it is in your code. However note that using scanf will take the part of the string till the first space or newline character.

This means if the user enters Hello World, then only Hello is taken by the code.

Add a comment
Know the answer?
Add Answer to:
Write a function that can return the length of a string in C language. Please leave...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT