Compile strlen functions without using library functions

Source: Internet
Author: User

Do not use library functions, or even use variables to write strlen functions, or other functions of strings are a common problem encountered during the test and interview.

Post belowCodeShare.

# Include <stdio. h> # include <stdlib. h> # include <string. h> int my_strlen1 (const char * Str) // recursion {return ('\ 0 '! = * Str )? (1 + my_strlen1 (++ Str): 0;} int my_strlen2 (const char * Str) // iteration {int COUNT = 0; while (* Str! = '\ 0') {count ++; STR ++;} return count ;}int main () {char * P; P = (char *) malloc (100 * sizeof (char); While (scanf ("% s", P )! = EOF) {int count1 = 0, count2 = 0, count3 = 0; count1 = my_strlen1 (p); count2 = my_strlen2 (p); count3 = strlen (P ); printf ("count1 = % d, count2 = % d, coont3 = % d \ n", count1, count2, count3);} Free (p); Return 0 ;}

The my_strlen1 function uses a recursive policy without any variables. When writing recursion, you must consider the recursive depth, which may sometimes cause stack overflow.

The my_strlen2 function uses simple iterations and is easy to understand.

 

There are other types of functions, such as writing two string-connected functions and string-Compared functions without using database functions.

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.