70. Implement Custom strlen Function

#include <stdio.h>

int custom_strlen(const char *str) {
    int length = 0;
    while (str[length] != '\0') {
        length++;  // Count until null terminator
    }
    return length;
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline if present
    int i = 0;
    while (str[i] != '\0') {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    printf("%d", custom_strlen(str));
    return 0;
}

What is this about?

This is the most fundamental string function in C — length is determined by counting characters until the '\0' null terminator is reached.

Why it’s important in firmware?

  • Bare-metal systems often avoid using string.h
  • Knowing string boundaries prevents buffer overflows
  • Used for custom protocol and buffer handling

Solution Logic

  • Loop through string using str[i] != '\0'
  • Count characters until null
  • No built-in library function used
     
Loading...

Input

Embedded

Expected Output

8