解题提升记录 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 String str = in.nextLine(); int count=0; for(int i=0 ; i<str.length() ; i++){ char char1 = str.charAt(i); if (char1 == ' '){ count = 0; }else{ count ++; } } System.out.print(count); } }
属于是一种简单粗暴的思路,逐个字符进行遍历,遍历到字母就count+1,遍历到空格就count清零。但前提条件是输出的字符得是符合英文规范的,也就是句子最后不会单独出现一个空格。自我感觉整个代码的唯一亮点在于使用了charAt函数