Thursday, June 7, 2012

strlen function in C

strlen string function is the one of the most common function used regularly to find the length of the string in C programming language. It returns the length of the string excluding (not including) null character or '\0'.  String library provides the inbuilt function for finding the length of the string and syntax is given below.

int strlen(const char *str);

Below is the sample code to find the length of string using strlen string function and later we will see our own function to find the string length.

main()
{
    char str[]="this is string";
    int len = strlen(str);
    printf("len is %d\n",len);
}

Output:
len is 14

strlen function definition: Below are the function for finding string length. I have given the code for finding strign length using both array and pointers.

strlen function with arrays:
int strlen_arry(char *str)
{
    int len=0;
    while(str[len]!='\0')
        len++;
    return len;
}

strlen function with pointers:
int strlen_ptr(char *str)
{
    int len=0;
    while(str!='\0')
    {
        str++;
        len++;
    }
    return len;
}

Explaination:  We will get the length of the string by counting the no. characters in the string. For this we need to traverse the string starting from zeroth character. In first method for arrays, we will traverse the string using index until reaches the null or terminal charater. Where as in second method for pointers ,we need to increase the pointer until pointer reaches the null or terminal characater.

No comments:

Popular Posts