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


import java.util.Scanner;
public class Main{
    public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    String s = in.nextLine();
    CodeLength(s);
     
}
public static void CodeLength(String s){
    String [] str = s.split(" ");
    int length = str.length;
    System.out.println(str[length-1].length());
}
}

    

 

方法二:

import java.util.*;
public class Main{
    public static int lengthOfLast(String str) {
        String[] s =str.split(" ");
        return s[s.length-1].length();
    }
     
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()){
            String str = scan.nextLine();
            System.out.println(lengthOfLast(str));
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM