How to use C language strlen function to read string length
Today Xiaobian to share with you how to use C language strlen function to read string length related knowledge points, detailed content, clear logic, I believe most people still know too much about this knowledge, so share this article for everyone to refer to, I hope you read this article after harvest, let's learn about it together.
strlenint main(){ char arr[] = "abcd"; int len = strlen(arr); printf("%d\n", len); return 0;}2, use pointer
String ends with character '\0', variable needs to be created
int my_strlen(char* str){ int count = 0;//Count the number of characters, you need to create a variable while (*str != '\0') { count++; str++; } return count;}int main(){ char arr[] = "abcd"; //char* str = arr; int len = my_strlen(arr); printf("%d\n", len); return 0;}3. Pointer improvements
Use pointer, do not create variables, do not need to create variables, interview question level, high requirements, difficult to master
int my_strlen(char* str){ char* p = str;//Record the location of the first element address while (*p != '\0') { p++; } return p - str;//tail address-the first address, that is, the length of the string}4, using recursion
Recursive function, do not need to create variables, in order to enlarge the small, decomposition, interview question level, high requirements, difficult to master
my_strlen("abcdef")
1+my_strlen("bcdef")
1+1+my_strlen("cdef")
1+1+1+ my_strlen("def")
1+1+1+1+ my_strlen("ef")
1 + 1 + 1 + 1 +1+my_strlen("f")
1 + 1 + 1 + 1 + 1 + 1+ my_strlen("")
1 + 1 + 1 + 1 + 1 + 1 + 0 = 6
int my_strlen(char* str){//No variable needs to be created if (*str != '\0') return 1 + my_strlen(str+1);//recursion else return 0;}5. Parameter improvement of my_strlen function-constant pointer
Define constant pointer, const limits the content of *str, the content of the string will not change when passing parameters, replace the above custom function with the following code:
int my_strlen(const char* str)//constant pointer {} The above is "How to use C language strlen function to read string length" All the contents of this article, thank you for reading! I believe everyone has a great harvest after reading this article. Xiaobian will update different knowledge for everyone every day. If you want to learn more knowledge, please pay attention to the industry information channel.