Search code examples
cstring-length

string length in c without using string library


    char* str =
    "\
    a-a-a-a\
    differing the text, because that was the lecture thing\
    the text has been changed\
    I know!\
    the text has been changed\
    ";

i deeply thinking about this for hours but can`t figure it out.. with using only stdio.h

string.h is not allowed, but using only basic things..

how can I get string length? someone please help me.

the goal is to find frequency of input pattern in a given string

ex) ha => 2, di => 1..

help me.


Solution

  • As for length of string, the implementation of strlen isn't very complicated.
    All you should do is to loop over the string until you find a \0 (end of string) and count the number of times you looped.

    unsigned int mystrlen(const char* str)
    {
        unsigned int length = 0;
        while (*str != 0)
        {
            str++;
            length++;
        }
        return length;
    }
    

    This could be shortened into

    unsigned int len = 0;
    for (; str[len]; len++);