diff --git a/DIRECTORY.md b/DIRECTORY.md index 74162d49..2bc57683 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -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) diff --git a/strings/strlen.c b/strings/strlen.c new file mode 100644 index 00000000..4ba7e9b2 --- /dev/null +++ b/strings/strlen.c @@ -0,0 +1,46 @@ +/** + * @file + * @brief Program to calculate length of string. + * + * @author [Du Yuanchao](https://github.com/shellhub) + */ +#include +#include + +/** + * @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; +} diff --git a/strings/strlen_recursion.c b/strings/strlen_recursion.c new file mode 100644 index 00000000..a55be950 --- /dev/null +++ b/strings/strlen_recursion.c @@ -0,0 +1,38 @@ +/** + * @file + * @brief Program to calculate length of string using recursion. + * + * @author [Du Yuanchao](https://github.com/shellhub) + */ +#include +#include + +/** + * @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; +}