🔹 Find String Length in C Using strlen() & Manual Method

⬅️ Back

đŸ’ģ Tutorial: Find Length of a String in C (With & Without strlen())

Learn how to calculate the length of a user-entered string in C by:

  • Using the built-in strlen() function
  • Manually counting characters without using any string functions

Method 1: Using strlen() Function

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove trailing newline character if present
    size_t len = strlen(str);
    if (len > 0 && str[len - 1] == '\n') {
        str[len - 1] = '\0';
        len--;
    }

    printf("Length of the string: %zu\n", len);

    return 0;
}

Explanation:

  • fgets() safely reads a string including spaces.
  • Trailing newline character from fgets() is removed.
  • strlen() returns the length excluding the null character.

Method 2: Manual Length Calculation Without strlen()

#include <stdio.h>

int main() {
    char str[100];
    int length = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Count characters until newline or null terminator
    while (str[length] != '\0' && str[length] != '\n') {
        length++;
    }

    printf("Length of the string: %d\n", length);

    return 0;
}

Explanation:

  • Reads input with fgets().
  • Manually counts characters until newline or string end.
  • This avoids using any built-in string function.

Summary

Both methods correctly calculate the string length. Use strlen() for convenience, or manual counting for understanding underlying logic.

C programming, string length in C, strlen example, manual string length calculation, fgets usage in C, beginner C tutorial, string functions in C, calculate length without strlen

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ