#include <stdio.h>
#include <string.h>
int main(void){
char str[100]="plus2net"; // input string
int str_length; // integer variable
str_length=strlen(str); // length of the string
printf("Length of the string = %d ", str_length); // final output
return 0;
}
The output of above code is here
Length of the string = 8
We can use string function strlen()
to get number of chars present in a string.
strlen(string);
#include <stdio.h>
#include <string.h>
int main(void){
char str[100]; // input string
int str_length; // integer variable
printf("Enter your string ");
scanf("%s",str);
str_length=strlen(str);
printf(" Length of the input string : %d", str_length); // printing outputs
return 0;
}
For input plus2net.com , output is 12
#include<stdio.h>
int main()
{
char str[12]="plus2net";
int i=0;
while (str[i] !='\0'){
// print value of i and value of string at that position. //
printf("i = %d : %c \n",i,str[i]); // Output
i=i+1; // increment of i by 1
}
return 0;
}
Output is here
i = 0 : p
i = 1 : l
i = 2 : u
i = 3 : s
i = 4 : 2
i = 5 : n
i = 6 : e
i = 7 : t
We know the length of the string is equal to value of our variable i. Here is the code to display the length.
#include<stdio.h>
int main()
{
char str[12]="plus2net";
int i=0;
while (str[i] !='\0'){
// print value of i and value of string at that position. //
printf("i = %d : %c \n",i,str[i]); // Output
i=i+1; // increment of i by 1
}
printf("Length of the string = %d ",i); // Output as length of the string
return 0;
}
This example demonstrates how to find the length of a string using strlen().
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "plus2net tutorials";
int len = strlen(str);
printf("The length of the string is: %d\n", len);
return 0;
}
Output:
The length of the string is: 18
---
This example shows how to use strlen() to calculate the length of a string entered by the user.
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // Remove newline character
printf("The length of the entered string is: %ld\n", strlen(str));
return 0;
}
Output:
Enter a string: plus2net
The length of the entered string is: 8
---
This example uses strlen() to iterate over a string and print each character.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "C programming";
int len = strlen(str);
for (int i = 0; i < len; i++) {
printf("Character at position %d: %c\n", i, str[i]);
}
return 0;
}
Output:
Character at position 0: C
Character at position 1:
Character at position 2: p
Character at position 3: r
Character at position 4: o
Character at position 5: g
Character at position 6: r
Character at position 7: a
Character at position 8: m
Character at position 9: m
Character at position 10: i
Character at position 11: n
Character at position 12: g