Write a program that takes a string as input and find the length of the string.
Program in C
C
#include <stdio.h>
#include <string.h>
int main() {
char input[100];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
// Remove trailing newline character
input[strcspn(input, "\n")] = '\0';
int length = strlen(input);
printf("Length of the string: %d\n", length);
return 0;
}
Explanation:
- In this program:
- We declare a character array input to store the user’s input string.
- The fgets function is used to read the user’s input, with a limit on the input length to prevent buffer overflow.
- We remove the trailing newline character from the input string using strcspn function.
- The strlen function is used to find the length of the input string.
- Finally, the length of the string is printed to the console.
Output:
C
Enter a string: EasyExamNotes.com
Length of the string: 17
Program in Java
Java
import java.util.Scanner;
public class StringLength {
public static void main(String[] args) {
String input;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
input = scanner.nextLine();
// Remove trailing newline character
input = input.trim();
int length = input.length();
System.out.println("Length of the string: " + length);
}
}
Explanation:
- import java.util.Scanner;: This line imports the Scanner class from the java.util package. It is used for reading user input.
- public class StringLength: This line declares a public class named StringLength.
- public static void main(String[] args): This is the main method that serves as the entry point of the program.
- String input;: This line declares a string variable named input to store the user input.
- Scanner scanner = new Scanner(System.in);: Creates a new Scanner object named scanner to read user input from the console.
- System.out.print(“Enter a string: “);: Prints a prompt message to enter a string.
- input = scanner.nextLine();: Reads the input string using scanner.nextLine().
- input = input.trim();: Removes leading and trailing whitespace from the input string using the trim() method.
- int length = input.length();: Retrieves the length of the input string using the length() method.
- System.out.println(“Length of the string: ” + length);: Prints the length of the string.
Output
Enter a string: EasyExamNotes.com
Length of the string: 17