Get the App
SLTechnology News&Howtos  ›  Development  › 

How to simulate and implement strlen function in C language

Shulou Source: shulou.com Published: 2022-05-31 23:57:24 09月14日 Update

This article mainly explains "C language how to simulate the implementation of strlen function", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's train of thought slowly in depth, together to study and learn "C language how to simulate the implementation of strlen function" bar!

I. introduction of strlen function declaration of 1.strlen function

Size_t strlen (const char * str)

Here the return value of the function is unsigned size_t, and a pointer of type char* is passed in.

Simple Application of 2.strlen function

The length of a string can be calculated by using the strlen function.

# include#includeint main () {char str [] = "qwerty"; int ret = strlen (str); printf ("length of string =% d\ n", ret); return 0;}

Result of code running

3. Matters needing attention

1. The string ends with'\ 0', and the strlen function returns the number of characters that appear before'\ 0' in the string (excluding'\ 0').

two。 The string pointed to by the parameter must end with'\ 0'.

If it does not end with'\ 0', the output will be a random value, for example:

# include#include int main () {char str [] = {'averse,' baked,'c'}; / / there is no ending with'\ 0' int ret = strlen (str); printf ("length of string =% d\ n", ret); return 0;}

Result of code running

In fact, the modification of this code is also very simple, such as:

Method 1

# include#include int main () {char str [] = {'averse,' baked, 'clocked,'\ 0'}; int ret = strlen (str); printf ("length of string =% d\ n", ret); return 0;}

Method 2 (if an array is not full, the following value defaults to 0, and the ASCII value of'\ 0' is 0)

# include#include int main () {char str [5] = {'a', 'baked,' c'}; int ret = strlen (str); printf ("length of string =% d\ n", ret); return 0;}

Result of code running

3. Note that the return value of the function is size_t, which is an unsigned shaping (error prone)

# include#include int main () {if (strlen ("abc")-strlen ("abcdefg") > 0) {printf (">\ n");} else {printf ("

Tags: Character pointer string function length method symbol result address counter recursion run language code number that is first word learning hee hee two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Microsoft macOS OPPO Reno vpn