Write function in C language, realize strlen function of calculating string length

Source: Internet
Author: User

This article describes three ways to:

1. Cyclic counting method, (set a counter).

2. Recursive method (function call itself for calculation)

3. Pointer-pointer method (this method is used by the library function)

Now included in the procedure:

Method 1:

/* Count Method */int My_strlen (char *p) {int number = 0;while (*p) {number++;p + +;} return number;}

Method 2:

/* Recursive */int My_strlen (char *str1) {if (*str1! = ') ') {Str1++;return 1 + my_strlen (STR1);} Elsereturn 0;}

Method 3:

/* Pointer subtraction */int my_strlen (char *p) {char *pstart = p;while (*p) P++;return P-pstart;}

Now give the main function a call and test:

int main () {char *str = "ASDFG"; int len = My_strlen (str);p rintf ("%d\n", Len); System ("pause"); return 0;}

The results are 5 and the results are correct!


If any of the great gods find that the procedure has yet to be improved, please criticize it!

This article is from the "Sharing Progress" blog, be sure to keep this source http://xmwen1.blog.51cto.com/10730069/1712765

Write function in C language, realize strlen function of calculating string length

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.