201k views
3 votes
Write a Java program to count the characters in each word in a given sentence?Examples:Input : geeks for geeksOutput :geeks->5for->3geeks->5

1 Answer

3 votes

Answer:

import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.print("Enter a sentence: ");

String sentence = in.nextLine();

String[] words = sentence.split("\\s");

for(String s : words)

System.out.println(s + " -> " + s.length());

}

}

Step-by-step explanation:

Ask the user to enter a sentence

Get each word in the sentence using split method and put them in words array

Loop through the words. Print each word and number of characters they have using the length method in required format

User Meena Alfons
by
6.9k points