C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Find string length (without strlen())

C Program: Find string length (without strlen())

Method 1: Using gets() function

C

#include <stdio.h>

 

int main() {

    char str[100];

    int i = 0, length = 0;

 

    // Input string

    printf("Enter a string: ");

    gets(str); // Note: unsafe, use fgets() in practice

 

    // Calculate length manually

    while (str[i] != '\0') {

        length++;

        i++;

    }

 

    // Display length

    printf("Length of the string: %d\n", length);

 

    return 0;

}

Output

 
INPUT :
Enter a string: ITDeveloper

OUTPUT :
Length of the string: 11

Explanation

  1. A string is stored in a character array str.
  2. A while loop runs through each character until it reaches the null terminator ('\0').
  3. The variable length counts the number of characters.
  4. Finally, the total length is printed.

 

C Program: Find string length (without strlen())

Method 2: Using fgets() function

C

#include <stdio.h>

 

int main() {

    char str[100];

    int i = 0, length = 0;

 

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);

 

    while (str[i] != '\0' && str[i] != '\n') {

        length++;

        i++;

    }

 

    printf("Length of the string: %d\n", length);

 

    return 0;

}

Output

 
INPUT :
Enter a string: ITDeveloper

OUTPUT :
Length of the string: 11

Explanation

  1. A string is stored in a character array str.
  2. A while loop runs through each character until it reaches the null terminator ('\0').
  3. The variable length counts the number of characters.
  4. Finally, the total length is printed.