牛客網——華為機試(題1:字符串最后一個單詞的長度)(Java)


題目描述:

計算字符串最后一個單詞的長度,單詞以空格隔開。 

輸入描述:

一行字符串,非空,長度小於5000。

輸出描述:

整數N,最后一個單詞的長度。

示例1:

輸入:

hello world

輸出:

5

代碼: 

import java.util.*;
public class Main {
    
     public static void main (String[] args) {
        Scanner in = new Scanner ( System.in );
        String word = in.nextLine();
        int n = word.lastIndexOf (" ");
        if ( n == -1)
            System.out.println( word.length() );
         else {
             String str = word.substring ( n ,word.length()-1 );
             System.out.println(str.length());
         }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM