Write a C-language program simulation to implement the Strlen function.
Algorithm
The function of the Strlen function is to calculate the number of characters in a string. (except for)
The string itself is an array of characters, except that the end ends with a.
Therefore, we only need to traverse all the characters except the.
There are three ways to solve this problem.
Algorithm Summary
Method One: Set an integer counter to traverse the string.
Method Two: Through the continuous function of its own recursion.
Method Three: Similar to method one, set a char* variable to mark the tail of the string, subtract the character length by subtracting the pointer.
Core code
Method one: By setting an integer counter, the simulation implements the Strlen function. int my_strlen1 (const char *str) {assert (str); int count = 0;while (*str++) {count++;} return count;} Method Two: Through recursion, the simulation implements the Strlen function int my_strlen2 (const char *str) {assert (str), if (*STR) {return (1+my_strlen2 (str+1));} return 0;} Method Three: Through the char* variable, the simulation implements the Strlen function int my_strlen3 (const char *str) {const char *end = Str;assert (str); while (*end++) {;} return (END-STR-1);}
Full Test code
/** This code copyright high Minor Blog All * Author: line does not rename, sit not change the name of the blogger high Minor * Date: 2015-7-31* code function: Three ways to simulate the implementation of strlen functions * collection: High-Minor blog-(http://gaoxiaodiao.com) */# Include
#include//method One: Simulates the implementation of the Strlen function by setting an integer counter. int my_strlen1 (const char *str) {assert (str); int count = 0; while (*str++) {count++;} return count;} Method Two: Through recursion, the simulation implements the Strlen function int my_strlen2 (const char *str) {assert (str), if (*STR) {return (1+my_strlen2 (str+1));} return 0;} Method Three: Through the char* variable, the simulation implements the Strlen function//(the Strlen function in the library function is so dry) int My_strlen3 (const char *str) {const char *end = Str;assert (str); while (*end++) {;} return (END-STR-1);} int main () {char str[]= "abcdef";p rintf ("str length is:%d\n", My_strlen1 (str));p rintf ("str length is:%d\n", My_strlen2 (str)); printf ("str length is:%d\n", My_strlen3 (str)); return 0;}
list of functions used in this code
- printf () function functions, prototypes, usages, and instances
- ASSERT () macro features, prototypes, usages, and instances
- Strlen () functions, prototypes, usages and examples
I wish you all the best in a minor.
This article by high minor blog original!
Original address: http://gaoxiaodiao.com/p/19.html
If you want to reprint, please specify the source!
C Language:: Simulation implements strlen function