C program to find the length of a string?


The string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.

To find the length of a string we need to loop and count all words in the loop until the ‘\0’ character is matched.

For example

Input: naman 

Output: string length is 6

Explanation: we need to iterate over each index of the string until reach the end of string means ‘\0’ which is null character. Due to null string is always +1 with no. of letters. Example, char ch[6] = {'n', 'a', 'm', 'a', 'n', '\0'};

Example

#include <stdio.h>
#include<string.h>
int main() {
   char string1[]={"naman"};
   int i=0, length;
   while(string1[i] !='\0') {
      i++;
   }
   length=i+1;
   printf(" string length is %d",length);
   return 0;
}

Output

string length is 6
raja
Published on 09-Aug-2019 12:39:39
Advertisements