两种思路:
- 使用BufferedReader 读取一行,end指针从后往前扫描直到指向的字符不是空格,定义start指针,从end位置开始往前扫描直到指向的字符是空格;
- 使用Scanner,由于Scanner本身的分割符就是空格,因此不断读取并直接输出最后读取到的字符串;
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); br.close(); int end = s.length() - 1; while (end > -1 && s.charAt(end) == ' ') { end--; } int start = end; while (start > -1 && s.charAt(start) != ' ') { start--; } System.out.println(end - start); } public static void withScanner() { Scanner sc = new Scanner(System.in); String s = ""; while (sc.hasNext()) { s = sc.next(); } System.out.println(s.length()); sc.close(); } }