niithub

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

给定由大写,小写字母和空格组成的字符串,返回最后一个单词的长度。

如果不存在最后一个单词,返回0

注意:

   “单词”是指不包含空格符号的字符串

例如:

   s = “hello World”, 那么返回的结果是5

格式:

   第一行输入字符串s,然后输出s中最后一个单词的长度。

样例输入

Today is a nice day

样例输出

3

=====================================
第一次code:

 1 import java.util.Scanner;
 2 
 3 public class Main
 4  {  
 5       public static void main (String[] args) 
 6       {  
 7           try
 8           {
 9               Scanner input = new Scanner(System.in);
10               System.out.println(prime(input.nextLine()));
11           }
12           catch(ArrayIndexOutOfBoundsException e)
13           {
14               System.out.println(0);
15           }
16       } 
17       public static int prime(String n)
18       {
19           int d = 0;
20           String [] a = n.split(" ");
21           String b = a[a.length-1];
22           char [] c = b.toCharArray();
23           d = c.length;
24           return d;
25       }
26  }

==================

第二次code:

 1 import java.util.Scanner;
 2 
 3 public class Main
 4  {  
 5        public static void main (String[] args) 
 6       {  
 7           Scanner input = new Scanner(System.in);
 8           if (input.hasNext()) 
 9           {
10                 String s = input.nextLine();
11                 System.out.println(prime(s));
12           } 
13           else 
14           {
15                 System.out.println(0);
16           }
17       }   
18       public static int prime(String n)
19       {
20           int d = 0;
21           String [] a = n.split(" ");
22           String b = a[a.length-1];
23           char [] c = b.toCharArray();
24           d = c.length;
25           return d;
26       }
27  }

posted on 2016-08-25 11:27  niithub  阅读(174)  评论(0编辑  收藏  举报