程式設計入門—Java語言 第六周編程題 1 單詞長度(4分)

來源:互聯網
上載者:User

標籤:寫法   imp   表達   長度   util   next   system.in   for   generate   

第六周編程題

 

依照學術誠信條款,我保證此作業是本人獨立完成的。

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 stubScanner 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 stubScanner in=new Scanner(System.in);String s=in.nextLine();char ch=‘.‘;String[] word=s.split("\\s{1,}");//Regex,一個或一個以上的空格for(int i=0;i<word.length-1;i++){System.out.print(word[i].trim().length()+" ");//用Regex後,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());}}}

  

程式設計入門—Java語言 第六周編程題 1 單詞長度(4分)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.