程序设计入门—Java语言 第六周编程题 1 单词长度(4分)

第六周编程题

 

依照学术诚信条款,我保证此作业是本人独立完成的。

1

单词长度(4分)

题目内容:

你的程序要读入一行文本,其中以空格分隔为若干个单词,以‘.’结束。你要输出这行文本中每个单词的长度。这里的单词与语言无关,可以包括各种符号,比如“it's”算一个单词,长度为4。注意,行中可能出现连续的空格。

 

输入格式:

输入在一行中给出一行文本,以‘.’结束,结尾的句号不能计算在最后一个单词的长度内。

 

输出格式:

在一行中输出这行文本对应的单词的长度,每个长度之间以空格隔开,行末没有最后的空格。

 

输入样例:

It's great to see you here.

 

输出样例:

4 5 2 3 3 4

时间限制:500ms内存限制:32000kb

import java.util.Scanner; 

public class hello
{

	public static void main(String[] args) 
	{
		// TODO Auto-generated method stub
		Scanner in=new Scanner(System.in);
		
		
		String s=in.next();
		char ch='.';
		while (s.length()>0)//采用分别读入每一个单词进行,
			//缺陷是如果语句中间输入的单词未尾是“.”就会视为语句结束,该写法未考虑有这种情况。
		{
			if(s.charAt(s.length()-1)==ch)
			{
				System.out.print((s.substring(0, s.length()-1)).length());
				break;
			}
			else
			{
				System.out.print(s.length()+" ");
				s=in.next();
			}
		}
	}
}

  方法二(更标准):

import java.util.Scanner; 

public class hello
{

	public static void main(String[] args) 
	{
		// TODO Auto-generated method stub
		Scanner in=new Scanner(System.in);
		String s=in.nextLine();
		char ch='.';
		String[] word=s.split("\s{1,}");//正则表达式,一个或一个以上的空格
		for(int i=0;i<word.length-1;i++)
		{
			System.out.print(word[i].trim().length()+" ");//用正则表达式后,trim()可以不要
		}
		String wend=word[word.length-1].trim();
		if(wend.charAt(wend.length()-1)==ch)
		{
			System.out.print(wend.substring(0, wend.length()-1).length());
		}
	}
}

  

原文地址:https://www.cnblogs.com/bcd589/p/6104393.html