Overview:
Before going to write the c program to get length of string, let's understand what String is? Then, I will demonstrate how to calculate the length of the string. After all, I will write the logic and C program to get the length of string with output.
Table of contents:
- What is String?
- Demonstration how to calculate the length of the string
- Logic to get length of string
- C program to get length of string with output
- Conclusion
What is String?
In C programming a string is a sequence of characters terminated with a null character 0.In other words, C String can be defined as the one-dimensional array of characters terminated by a null ('\0') character. For example, the length of the string "C programming" is 13 (space character is counted).
Demonstration of how to calculate the length of the string
String length is counted by counting of its characters with spaces. for example, the length of the string "C programming" is 13 (space character is counted). To find the length of the string we will use strlen() of string.h header file. You can declare the string in C programming as follows:
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Array initialization is done as follows: char greeting[] = "Hello";
Logic to get length of string
- Step 1: Input a string from user.
- Step 2: Store it in to some variable say text.
- Step 3: Initialize a counter variable to zero, say count = 0.
- Step 4: Count variable is used to store total number of characters in the string, which is our effective length of string.
- Step 5: To iterate through input string, run a loop from 0 to the last character of string i.e. NULL character.
- Step 6: The loop structure should look like for(i=0; text[i]!='\0'; i++).
- Step 7: Inside the loop increment the counter variable with 1 i.e. count++.
C Program to calculate the length of string by using loop
#include <stdio.h> #include <string.h> int main() { char Str[1000]; int i; printf("Enter the String: "); scanf("%s", Str); for (i = 0; Str[i] != '\0'; ++i); printf("Length of String is %d", i); return 0; } Output: Enter the String: Hello Length of String is 5
C Program to find the length of the string by using strlen()
// C program to find the length of // string using strlen function #include <stdio.h> #include <string.h> int main() { char Str[1000]; int i; printf("Enter the String: "); scanf("%s", Str); printf("Length of Str is %ld", strlen(Str)); return 0; } Output: Enter the String: Hello Length of String is 5
Conclusion:
In this program, using a for loop, we have iterated over characters of the string from i = 0 to until '\0' (null character) is encountered. In each iteration, the value of i is increased by 1. When the loop ends, the length of the string will be stored in the i variable.