Home > Blockchain >  Creating an strlen function in c
Creating an strlen function in c

Time:11-26

the mission is to create a function that replaces strlen but in the order I'll present you'd have to fill the empty spots. I tried something but got stuck where I need to count the size and return it.

#include <stdio.h>
#define MAXLENGTH 80

int my_strlen(char* s)
{
    char *p = (1);
    while (2)
        (3);

    return (4);
}


int main()
{

    char str[MAXLENGTH];
    int len;
    printf("Enter a string:");
    gets(str);
    len = my_strlen(str);
    printf("The length of the string %s is %d\n", str, len);
}

I tried this but got stuck at 3, how to count the size

#include <stdio.h>
#define MAXLENGTH 80

int my_strlen(char* s)
{
    char *p = s;
    while (*p   != '\0')
        (3);

    return (4);
}


int main()
{

    char str[MAXLENGTH];
    int len;
    printf("Enter a string:");
    gets(str);
    len = my_strlen(str);
    printf("The length of the string %s is %d\n", str, len);
}

CodePudding user response:

size_t mystrlen(const char *restrict s)
{
    const char *restrict e = s;
    while(*e) e  ;

    return (uintptr_t)e - (uintptr_t)s;
}

But I would not advice to show it your teacher.....

CodePudding user response:

I've just replaced your (3) and (4) with i that will increment until termination (\0) and will return (i).

#include <stdio.h>
#define MAXLENGTH 80

int my_strlen(char* s)
{
    int i=1;
    char *p = s;
    while (*p  )
        i  ;

    return (i);
}


int main()
{

    char str[MAXLENGTH];
    int len;
    printf("Enter a string:");
    gets(str);
    len = my_strlen(str);
    printf("The length of the string %s is %d\n", str, len);
}

returning value will be 1 (including \0)

  • Related