C language to find the length of the string of several methods of implementation

  • 2020-06-07 05:02:54
  • OfStack

1. The most common method is to create a counter to determine if '\0' is encountered, and if it is not '\0' the pointer is incresed by 1.


int my_strlen(const char *str)
{
	assert(str != NULL);
	int count = 0;
	while (*str != '\0')
	{
		count++;
		str++;
	}
	return count;
}

2. Do not create a counter, go through 1 from front to back, do not encounter '\0' let the pointer add 1 backwards, find the last 1 character, write down the address, then use the address of the last 1 character minus the starting address, get the length of the string.


int my_strlen(const char *str)
{
	char *end = str;
	assert(str!=NULL);
	assert(end!=NULL);
	while (*end != '\0')
	{
		end++;
	}
	return end - str;
}

3. Do not create counters and implement recursively.


int my_strlen(const char *str)
{
	assert(str != NULL);
	if (*str == '\0')
	{
		return 0;
	}
	else
	{
		return (1 + my_strlen(++str));
	}
}

Or you could write it like this:


int my_strlen(const char *str)
{
	assert(str != NULL);
	return (*str == '\0') ? 0 : (my_strlen(++str) + 1);
}

Or this:


int my_strlen(const char *str)
{
	assert(str != NULL);
	return (*str == '\0') ? 0 : (my_strlen(str+1) + 1);
}

That's the end of the c function for getting the length of a string.


Related articles: