Added strlen function (#606)

* added strlen function

* updating DIRECTORY.md

* Update strings/strlen.c

Co-authored-by: David Leal <halfpacho@gmail.com>

* Update strings/strlen_recursion.c

Co-authored-by: David Leal <halfpacho@gmail.com>

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Du Yuanchao 2020-09-24 02:22:09 +08:00 committed by GitHub
parent 88726b9425
commit 598630cecb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 88 additions and 0 deletions

View File

@ -382,3 +382,7 @@
* [Shell Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/shell_sort.c)
* [Shell Sort2](https://github.com/TheAlgorithms/C/blob/master/sorting/shell_sort2.c)
* [Stooge Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/stooge_sort.c)
## Strings
* [Strlen](https://github.com/TheAlgorithms/C/blob/master/strings/strlen.c)
* [Strlen Recursion](https://github.com/TheAlgorithms/C/blob/master/strings/strlen_recursion.c)

46
strings/strlen.c Normal file
View File

@ -0,0 +1,46 @@
/**
* @file
* @brief Program to calculate length of string.
*
* @author [Du Yuanchao](https://github.com/shellhub)
*/
#include <assert.h>
#include <string.h>
/**
* @brief Returns the length of string
* @param str the pointer of string.
* @return the length of string.
*/
int length(const char *str)
{
int count = 0;
for (int i = 0; *(str + i) != '\0'; ++i)
{
count++;
}
return count;
}
/**
* @brief Test function
* @return void
*/
static void test()
{
assert(length("") == strlen(""));
assert(length(("a")) == strlen("a"));
assert(length("abc") == strlen("abc"));
assert(length("abc123def") == strlen("abc123def"));
assert(length("abc\0def") == strlen("abc\0def"));
}
/**
* @brief Driver Code
* @returns 0 on exit
*/
int main()
{
test();
return 0;
}

View File

@ -0,0 +1,38 @@
/**
* @file
* @brief Program to calculate length of string using recursion.
*
* @author [Du Yuanchao](https://github.com/shellhub)
*/
#include <assert.h>
#include <string.h>
/**
* @brief Returns the length of string using recursion
* @param str the pointer of string.
* @return the length of string.
*/
int length(const char *str) { return *str == '\0' ? 0 : 1 + length(++str); }
/**
* @brief Test function
* @return void
*/
static void test()
{
assert(length("") == strlen(""));
assert(length(("a")) == strlen("a"));
assert(length("abc") == strlen("abc"));
assert(length("abc123def") == strlen("abc123def"));
assert(length("abc\0def") == strlen("abc\0def"));
}
/**
* @brief Driver Code
* @returns 0 on exit
*/
int main()
{
test();
return 0;
}