Problem: Write a C program to find the length of a given string. The program should prompt the user to enter a string and then calculate and display the length of the string.
Example:
Input: Hello, World! Output: 13 Input: Algolesson Output: 10
There are two different ways to calculate the length of the string in C programming:
- Using loop.
- Using buit-in function strlen.
Key Note: Strings in C are represented as arrays of characters, terminated by a null character ('\0'). The length of a string is the number of characters before the null-terminating character. (alert-passed)
Approach 1: Find the Length of the string using a loop.
In this approach, we will calculate the length of a string manually by iterating through each character of the string until we encounter the null-terminating character ('\0').
Below is the code implementation of the above approach:
C Code:
//C Program to Find the length of the given string #include <stdio.h> // Function to find the length of a string int customStringLength(const char *str) { int length = 0; while (*str != '\0') { length++; str++; } return length; } int main() { char inputString[100]; printf("Enter a string: "); scanf("%[^\n]", inputString); // function to calculate the length int length = customStringLength(inputString); printf("Length of the string: %d\n", length); return 0; }
Enter a string: Welcome to AlgoLesson
Length of the string: 21
Time Complexity: O(n) where n is the number of characters present in the string.
Space Complexity: O(1) as no extra space is required to solve this problem.
Approach 2: Using Built-in Function strlen.
In this approach, we are going to use one built-in function strlen() to find the length of the string. The strlen() function is defined in the string.h header and is used to calculate the length of a given string.
Below is the code implementation for the above approach:
C Code:
// C program to find length of string uisng built-in function #include <stdio.h> #include <string.h> int main() { char inputString[100]; printf("Enter a string: "); scanf("%[^\n]", inputString); // Using strlen() function to calculate the length int length = strlen(inputString); printf("Length of the string: %d\n", length); return 0; }
Enter a string: Hello World
Length of the string: 11
In this code, we include the string.h header and then use the strlen() function directly to calculate the length of the input string. This approach is simpler and more efficient compared to manually iterating through the string.
Time Complexity: O(n)
Space Complexity: O(1)
No comments:
Post a Comment