Write Functions in C language to implement strlen's function of calculating the string length

Source: Internet
Author: User

Write Functions in C language to implement strlen's function of calculating the string length
This article introduces three methods: 1. Cyclic notation (set a counter ). 2. Recursive Method, (function call itself for calculation) 3. pointer-pointer method (library function uses this method) is now included in the program: Method 1:

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

 

Method 2:
/* Recursion */int my_strlen (char * str1) {if (* str1! = '\ 0') {str1 ++; return 1 + my_strlen (str1) ;}else return 0 ;}

 

Method 3:
Int main () {char * str = "asdfg"; int len = my_strlen (str); printf ("% d \ n", len); system ("pause "); return 0 ;}

 

Now we provide the main function for calling and testing:
Int main () {char * str = "asdfg"; int len = my_strlen (str); printf ("% d \ n", len); system ("pause "); return 0 ;}

 

After verification, all results are 5, and the calculation result is correct! If any great God finds that the program is still to be improved, please criticize and correct it!

Related Article

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.