Length of string in C

Program to find length of string in C language using the library function strlen() . Also, includes example of length of string in C programming with user input string.

It should be noted that the length of an string can also be calculated without using strlen function.

C program to find length of string using strlen function

/*---------------------------------------------------
* Program to find length of string in C using strlen
*/


#include <stdio.h>

int main(){

	int len;
	//String
	char str[32] = "Hello world";
	
	//get length of string
	len = strlen(str);

	printf("Length of String :[%s] is :%d",str,len);
	

	return 0;
}

Output:
Length of String :[Hello world] is :11

Program for string length using user input and with strlen() function

NOTE:

To read the input string e.g. Hello World, in scanf function, we need to use the expression scanf(“%[^\n]s”, str); – notice the [^\n].It will read the string including space. If we use simple like scanf(“%s”, str);to read string, then only first word e.g. in hello world, only hello will be read by scanf.

/*----------------------------------------------
* Program to find length of string in C using
* User input and strlen() library function
*/


#include <stdio.h>

int main(){

	int index, str_length;

	//Create char buffer to store string
	char str[32];

	printf("\nEnter string: ");

	//Note that only %s in scanf read first word and
	//not able to handle space in string

	//So, if we use [^\n] in it will handle space also.
	scanf("%[^\n]s", str);

	//Get length of the entered string
	str_length = strlen(str);

	printf("Length of String :[%s] is :%d",str,str_length);
	

	return 0;
}

Output:
Enter string: hello world
Length of String :[hello world] is :11

Length of string in C

Scroll to top