在一行上输入若干个字符串,每个字符串代表一个单词,组成给定的句子。
除此之外,保证每个单词非空,由大小写字母混合构成,且总字符长度不超过
。
在一行上输出一个整数,代表最后一个单词的长度。
HelloNowcoder
13
在这个样例中,最后一个单词是
,长度为
。
A B C D
1
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String inupt = in.nextLine(); int lastwordLoc = inupt.lastIndexOf(" "); System.out.println(inupt.length()-lastwordLoc-1); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println(lengthOfLastWord(scanner.nextLine())); } public static int lengthOfLastWord(String str) { int len = str.length(); int left = 0; for (int i = len - 1; i >= 0; i--) { if (str.charAt(i) == ' ') { left = i + 1; break; } } return len - left; } }
import java.io.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; int length = 0; char c; while((c=(char)inputStream.read()) != '\n'){ length++; if(c == ' '){ length = 0; } } System.out.print(length); } }
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String s = in.nextLine(); System.out.println(test(s)); } } private static int test(String s){ if(s.length() == 0) return 0; for(int i = s.length() - 1; i >= 0; i--){ if(s.charAt(i) == ' ') return s.length() - 1 - i; } return s.length(); } }
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // String string = in.nextLine(); String s = string.substring(string.lastIndexOf(" ") + 1); System.out.println(s.length()); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNextLine()) { String str = in.nextLine(); int lastIndexOf = str.lastIndexOf(" "); System.out.println(str.length() - lastIndexOf - 1); } } }
public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 String word = in.nextLine(); String[] strArr = word.split(""); int num = 0; int i = strArr.length - 1; while (" ".equals(strArr[i])){ i--; } for (; i >= 0; i--) { if (!" ".equals(strArr[i])) { num++; } else { break; } } System.out.println(num); }