arrayscharsizeofstring-length

How can I count the length of char in a char array without using any loop?


so i was practicing my c language and there i come to a need that how can i count the length of character in a character array because when i use sizeof() in that i got the whole length of array..although i can use "for loop" but i can't use that in that question so is there any other way to do this..

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

int main()
{
    int i,N;
    char a[20];
    printf("enter the string");
    scanf("%s",a);
    puts(a);
    N = sizeof(a); 
    printf("%d",N);
    return 0;
}

OUTPUT:-

enter the string                                                                                     
helloguys                                                                                            
helloguys                                                                                            
20     

Solution

  • This can be achieved in 2 ways:

    1) Using strlen() function defined in string.h:

    #include <stdio.h>
    #include<string.h>
    #include<math.h>
    
    int main()
    {
        int i,N;
        char a[20];
        printf("enter the string");
        scanf("%s",a);
        puts(a);
        N = strlen(a); 
        printf("%d",N);
        return 0;
    }
    

    Be aware that, strlen() uses loop internally. According to the definition of strlen() in string.h library, the possible implementation as per cppreference.com is:

    std::size_t strlen(const char* start) {
        const char* end = start;
        while(*end++ != 0);
        return end - start - 1;
    }
    

    Therefore the second way without using using loops directly or indirectly can be recursion.

    2) Using recursion:

    #include <stdio.h>
    #include<string.h>
    #include<math.h>
    
    int LengthofString(char *string) 
    {  
        if (*string == '\0')  
            return 0; 
        else
            return 1 + LengthofString(string + 1); 
    }
    
    int main()
    {
        int i,N;
        char a[20];
        printf("enter the string");
        scanf("%s",a);
        puts(a);
        N = LengthofString(a);
        printf("%d",N);
        return 0;
    }
    

    PS: Beware about the predefined library functions and their internal implementations before using them.