String Length in C Program

Every string in a c program is actually a NULL terminated character array. So if we initialize an array like this:
char str[] = "HELLO WORLD";
it will be stored in the memory like this:
H
E
L
L
O

W
O
R
L
D
\0
That is, a NULL Character ( \0 ) will be put automatically at the end of the string.  So if we count the number of characters till the NULL character, then we will get the length of our string. Here is the way to do that:

String Length Without Using Library Function:
#include <stdio.h>

int main()
{
    char str[1000];
    int i, count = 0;
    printf("Enter a string: ");
    gets(str);
    for(i=0;i<1000;i++) {
        if(str[i] == '\0')
            break;
        count++;
    }
    printf("There are %d characters in the given string.", count);
    return 0;
}

String Length using Library Function:

There is actually a library function to get the string length. The function is strlen(char *) and this function is in the header file string.h. Here is an example:

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

int main()
{
    char str[1000];
    int len;
    printf("Enter a string: ");
    gets(str);
    len = strlen(str);
    printf("There are %d characters in the given string.", len);
    return 0;
}

1 comments :

Spam comments will be deleted. :)

 
Loading...
TOP