今天遇到一個面試題,描述如下:
計算字符串最后一個單詞的長度,單詞以空格隔開。
其實很簡單:
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.println(getLastWordLen(scan.next())); } public static int getLastWordLen(String str){ int i = str.lastIndexOf(" ")+1; String lastWord = str.substring(i); return lastWord.length(); } }
but.....,測試一下發現並不對。隨便輸入一個“123 12”,結果應該是2,實際卻輸出3,百思不得姐,一度查看lastIndexOf源碼,依然不明白咋回事。最后發現問題出在scan.next(),這個方法不支持控制台輸入帶有空格的字符串,例如輸入“123 12”,實際上只能接收到“123”,空格后面的被截掉了,改成scan.nextLine(),問題解決。
控制台輸入再入新坑
System.out.println(scan.next()) ;
System.out.println(scan.nextLine()) ;
這樣寫,我覺得人畜無傷,實際上第一次輸入完成后,還沒等我再次輸入,就結束了。
盜用人家的成果https://blog.csdn.net/superme_yong/article/details/80543995。nextLine()換成nextInt()也不行,所以還是盡量用同一種next方法吧。