asked 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

answered
User Meena Alfons
by
8.7k points

Related questions

1 answer
1 vote
49.4k views
asked Aug 17, 2024 101k views
Sonarholster asked Aug 17, 2024
by Sonarholster
8.6k points
1 answer
1 vote
101k views