C Language: Custom strlen() function
C - Implementing a custom strlen() function
The strlen() function is used to get the length of a string excluding the ending null character.
Here's an implementation of a custom strlen() function:
Code:
#include <stdio.h>
size_t custom_strlen(const char* str) {
size_t len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}
int main() {
char str[] = "C Snippets";
size_t len = custom_strlen(str);
printf("Length of the string is %lu\n", len);
return 0;
}
Output:
Length of the string is 10
In the custom_strlen() function, we start with len = 0 and iterate through the string until we reach the null character '\0'. In each iteration, we increment "len" and move the pointer to the next character. Finally, we return the length of the string.
In the main() function, we declare a character array str with the string "C Snippets" call custom_strlen() to find its length, and print the length.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join