Today’s task is to write a program that counts the number of characters in a given string entered by the user. This exercise will introduce you to working with strings, input handling, and string functions in your programming language of choice.
The goal is to:
For example:
"Hello, World!"
has 13 characters (including spaces and punctuation)."abc123"
has 6 characters.Most programming languages provide built-in functions to determine the length of a string.
Python: Use the len()
function.
length = len(string)
Java: Use the .length()
method.
int length = string.length();
JavaScript: Use the .length
property.
let length = string.length;
Prompt the user to enter a string.
Python:
string = input("Enter a string: ")
Java:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String string = scanner.nextLine();
JavaScript:
let string = prompt("Enter a string:");
Use the appropriate function or property to find the length of the string.
Print the length of the string in a user-friendly way.
# Get user input
string = input("Enter a string: ")
# Calculate the length of the string
length = len(string)
# Display the result
print(f"The length of the string is: {length}")
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Get user input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String string = scanner.nextLine();
// Calculate the length of the string
int length = string.length();
// Display the result
System.out.println("The length of the string is: " + length);
}
}
// Get user input
let string = prompt("Enter a string:");
// Calculate the length of the string
let length = string.length;
// Display the result
console.log("The length of the string is: " + length);
0
.""
The length of the string is: 0
" "
The length of the string is: 3
@
, #
, !
) and numbers should also be counted."123!@#"
The length of the string is: 6
len()
, .length()
, and .length
to calculate the length of a string.Once you’ve completed this program, try extending it:
.replace()
(Python/JavaScript) or replaceAll()
(Java).By completing this challenge, you’re building a solid foundation in string manipulation—an essential skill for solving real-world coding problems!