w3resource

C Programming: Find the length of a string


2. String Length Without Library

Write a program in C to find the length of a string without using library functions.

C Programming: Find the length of a string


Sample Solution:

C Code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[100]; /* Declares a string of size 100 */
    int l = 0; // Initialize a variable to store the length of the string
	
    printf("\n\nFind the length of a string :\n"); // Display information about the task
    printf("---------------------------------\n"); 	
    printf("Input the string : ");

    // Read a string from the standard input (keyboard) using fgets()
    fgets(str, sizeof str, stdin);

    // Loop to calculate the length of the string
    while (str[l] != '\0') {
        l++; // Increment the length counter until the null terminator '\0' is encountered
    }

    printf("Length of the string is : %d\n\n", l - 1); // Display the length of the string
	
	return 0; // Return 0 to indicate successful execution of the program
}

Output:

Find the length of a string :                                                                                 
---------------------------------                                                                             
Input the string : w3resource.com                                                                             
Length of the string is : 15 

Flowchart:

Flowchart: Find the length of a string.


For more Practice: Solve these Related Problems:

  • Write a C program to compute the length of a string recursively without using any library functions.
  • Write a C program to determine the length of a string using pointer arithmetic without looping explicitly.
  • Write a C program to calculate a string’s length by iterating over its characters until the null terminator is reached.
  • Write a C program to read a string from a file and calculate its length manually without library support.

Go to:


PREV : String Input Prin.
NEXT : Separate String Characters.

C Programming Code Editor:



Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.