Sunday, April 17, 2016

Java Program: Word Length

The program is to read a line of text, which is divided into several words by spaces and ends with '.'. You should output the length of each word in this line of text. The words here have nothing to do with language, which include a variety of symbols. For example, "it's" is a word, whose length is 4. Note that there may be continuous spaces in the row.
 
Input format:
 
Enter a line of text ending with '.' in a row, but '.' can not be calculated in the last word length.
 
Output format:
 
Output the lengths of each word corresponding to this line of text in one line, every 2 length divided by a space. There are no spaces at the end of the line.
 
Input sample:
 
It's great to see you here.
 
Output sample:
4 5 2 3 3 4

Here is my program.

 //Word Length
import java.util.Scanner;

public class Main {
   
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        int count = 0, i;
        boolean isFirst = true;
        for (i=0;i<s.length()-1;)
        {
            while (s.charAt(i)==(' '))
                i++;
            while (s.charAt(i)!=('.')&&s.charAt(i++)!=(' '))
                count++;
            if (isFirst)
            {
                System.out.print(count);
                isFirst = false;
            }
            else
                System.out.print(" "+count);
            count = 0;
        }
    }
}

No comments:

Post a Comment