计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)
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); }
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s= in.nextLine(); String[] arr=s.split(" "); int n=arr.length; System.out.println(arr[n-1].length()); } }