字串最后一個單詞的長度
你既然已經做出了選擇,又何必去問為什么選擇?
背景: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 }
輸出驗證:

你既然已經做出了選擇
又何必去問為什么選擇
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/1909.html
標籤:Java
