标签:
注意空格的情况:连续多个空格;一行字符串的尾部有空格。
1 import java.util.Scanner; 2 3 public class Main { 4 5 public static void main(String[] args) { 6 7 Scanner scanner = new Scanner(System.in); 8 9 while (scanner.hasNextLine()) { 10 11 String input = scanner.nextLine(); 12 int result = Main.count(input); 13 System.out.println("count:" + result); 14 } 15 } 16 17 public static int count(String str) { 18 19 int num = 0; 20 int flag = 0; 21 char[] array = str.toCharArray(); 22 23 for (int i = 0; i < array.length; i++) { 24 if (array[i] == ‘ ‘ && flag == 0) { 25 num++; 26 flag = 1; 27 } else if (array[i] != ‘ ‘) { 28 flag = 0; 29 } 30 } 31 32 if (‘ ‘ == array[array.length - 1]) { 33 return num; 34 } else { 35 return num + 1; 36 } 37 } 38 }
标签:
原文地址:http://www.cnblogs.com/jiangyi-uestc/p/5797681.html