计算字符串最后一个单词的长度,单词以空格隔开

来源:互联网 发布:菜鸟阎王网络剧百度云 编辑:程序博客网 时间:2024/05/18 00:40
//思路:1从后向前计算,遇到空格停止。

//2.正则表达式分割

一:

import java.lang.*;
 import java.util.*;
public class Main{

 public static void m1(String[] args)
    { Scanner scan=new Scanner(System.in);
      String str=null;
     while(scan.hasNextLine())
     {
       str=scan. nextLine();  
      }
      System.out.println( lastLength(str));
    }
 
    public static  int lastLength(String str)
    { int length=0;
        for(int i=str.length()-1;i>=0;i--)
        {
            
           if(str.charAt(i)==' ')
               break;
           length++;
         
        }
     return length;
    }
    }

二:
    public static void main(String[] args)
    { 

    Scanner scan=new Scanner(System.in);
      String str=null;
     while(scan.hasNextLine())
     {
       str=scan. nextLine();  
      }
      String[] s=str.split("\\s");


     System.out.println(s[s.length-1].length());
    }
         

0 0
原创粉丝点击