×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to calculate length of the string without using strlen()

The strlen() is a library function of string.h that returns length of the string.

Problem statement

Here, we will calculate length of the string without using strlen() function.

Steps to calculate length of the string

  • Read a string
  • Create a function and pass string within it
  • Take a counter as length (that will store the length of the string), initialize with 0
  • Run a loop until NULL character is not found
  • Increase the counter (length)
  • As NULL founds return the length

C program to calculate length of the string without using strlen()

#include <stdio.h>

/*function to return length of the string*/
int stringLength(char*);

int main() {
  char str[100] = {0};
  int length;

  printf("Enter any string: ");
  scanf("%s", str);

  /*call the function*/
  length = stringLength(str);

  printf("String length is : %d\n", length);

  return 0;
}

/*function definition...*/
int stringLength(char* txt) {
  int i = 0, count = 0;

  while (txt[i++] != '\0') {
    count += 1;
  }

  return count;
}

Output

Enter any string: IncludeHelp 
String length is : 11

C Strings User-defined Functions Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.