Home > other >  How to find the length of a string char[] in c without using a library. (Not even c standard)
How to find the length of a string char[] in c without using a library. (Not even c standard)

Time:03-13

I want to use no libraries at all (not even c standard) and find how long a string is in an array of characters.

CodePudding user response:

It's a matter of counting the characters in the array before you find the first \0, something like:

unsigned int StrLen(char *str) {
    unsigned int len = 0;
    while (*str != '\0') {
        str  ;
        len  ;
    }
    return len;
}

CodePudding user response:

The answer you want is probably paxdiablo's, but here is another way albeit much more restricted. You can use sizeof for your statically allocated arrays.

char str[] = "12345";
unsigned int size = sizeof str; // will return 6: 5  1 for null-termiantor

Beware that this method doesn't look for the null-terminator, instead it returns the allocated memory, so:

char arr[10] = { 0 };
arr[0] = 'a';
arr[1] = '\0';

unsigned int size = sizeof arr; // will return 10, not 2. 

It also won't work with dynamically allocated arrays

char *arr = malloc( 5 * sizeof *arr );

unsigned int size = sizeof arr; // is the same as sizeof *char
                                // simply returns the size of a char pointer in your system.  
  • Related