字符串最后一個單詞的長度


字符串最后一個單詞的長度

       你既然已經做出了選擇,又何必去問為什么選擇?

 

背景:Java 在線編程機試刷題。

題目描述:

計算字符串最后一個單詞的長度,單詞以空格隔開。 

輸入描述:

一行字符串,非空,長度小於5000。

輸出描述:

整數N,最后一個單詞的長度。

示例1

輸入:

hello word

輸出:

5

Java代碼:

 1 import java.util.Scanner;  2 public class Main{  3     
 4     private static void countLastWordLength(String str){  5        if(!str.isEmpty()){  6            String [] split = str.split(" ");  7            String lastWord = split[split.length - 1];  8            int length = lastWord.length();  9  System.out.print(length); 10  } 11  } 12     
13     public static void main(String [] args){ 14         Scanner scan = new Scanner(System.in); 15         while(scan.hasNext()){ 16             String input = scan.nextLine(); 17  countLastWordLength(input); 18  } 19  } 20     
21 }

輸出驗證:

 

 

 

你既然已經做出了選擇

又何必去問為什么選擇

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM