can you write a java program that will count the number of letters, digits , spaces and…
- User
can you write a java program that will count the number of letters, digits , spaces and punctuation marks in a string?
- Assistant
Certainly! Here's a Java program that counts the number of letters, digits, spaces, and punctuation marks in a given string:
import java.util.Scanner; public class CharacterCount { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); scanner.close(); int letterCount = 0; int digitCount = 0; int spaceCount = 0; int punctuationCount = 0; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (Character.isLetter(c)) { letterCount++; } else if (Character.isDigit(c)) { digitCount++; } else if (Character.isSpaceChar(c)) { spaceCount++; } else if (Character.isWhitespace(c)) { spaceCount++; } else if (Character.isJavaIdentifierPart(c)) { letterCount++; } else { punctuationCount++; } } System.out.println("Number of letters: " + letterCount); System.out.println("Number of digits: " + digitCount); System.out.println("Number of spaces: " + spaceCount); System.out.println("Number of punctuation marks: " + punctuationCount); } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.