题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
import java.util.*; public class Main { /** 1. 从输入流中获取用户输入。 2. 使用 hasNextLine 获取一整行的输入。 3. 逆向循环字符串,当遇到空格时,返回字符串长度与当前位置的差。 */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); String strs = ""; while (scan.hasNextLine()) { strs = scan.nextLine(); } scan.close(); System.out.println(getLastStrLen(strs)); } private static int getLastStrLen(String strs) { for (int i = strs.length()-1; i >= 0; i--) { if (strs.charAt(i) == ' ') { return strs.length() - i - 1; // -1 因为要把空格长度排除 } } return strs.length(); } }