String Length Calculator in C

This code snippet demonstrates how to calculate the length of a string in C using a custom function called my_strlen. It prompts the user to enter a string, processes the input to remove any trailing newline characters, and then outputs the length of the entered string using the custom function.
mail@pastecode.io avatar
unknown
c_cpp
a month ago
727 B
3
Indexable
Never
#include <stdio.h>

// Function to calculate the length of a string
int my_strlen(const char *str) {
    int length = 0;
    while (*str != '\0') {
        length++;
        str++;
    }
    return length;
}

int main() {
    char my_string[100];

    // Taking user input
    printf("Enter a string: ");
    fgets(my_string, sizeof(my_string), stdin);

    // Removing trailing newline if exists (caused by fgets)
    if (my_string[my_strlen(my_string) - 1] == '\n') {
        my_string[my_strlen(my_string) - 1] = '\0';
    }

    // Calculating length using my_strlen
    int length = my_strlen(my_string);

    // Outputting the length of the string
    printf("The length of the string is: %d\n", length);

    return 0;
}
Leave a Comment