字符串最后一个单词的长度


字符串最后一个单词的长度

       你既然已经做出了选择,又何必去问为什么选择?

 

背景: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