题目
方法1-A
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String[] s = str.split(" ");
int length = s[s.length - 1].length();
System.out.println(length);
}
}
总结: 1、这就是基础、需要巩固java基础
方法1-B
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String[] s = str.split("\\s+"); //正则比" "多用3毫秒
int length = s[s.length - 1].length();
System.out.println(length);
}
}
总结:
1、正则一般会比字符串直接匹配慢、对慢的时间有个概念会慢几毫秒
2、\s等价于 [ \f\n\r\t\v] 和空格、参考来源: 正则表达式转义字符一览
3、Java中一个\代表转义,\加上如下符号 \, ^, $, ., ?, +, *,|,(, ), {, }, [, ] 表示这些字符本身。java里\\[ 第一个\只是对后面\的转义,故对[ 的匹配需要用两个\
参考来源
方法2
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int length = str.length();
int count = 0;
for (int i = length - 1; i >= 0; i--) {
if (str.charAt(i)==' ') {
break;
}
count++;
}
System.out.println(count);
}
}
总结: 已总结到 通过编辑统计数量的几种思路
1、如下代码块是个统计数量通用思路
int total = 0; // 总数记录器
for (int i = str.length() - 1; i >= 0; i--) { // 遍历从最后一项到第一项
if (str.charAt(i) == ' ') { // 终止条件
break; // 跳出循环
}
total++; // 符合条件 总数+1
}
终止条件 + 终止处理(跳出循环) + 抽取重复操作(符合条件 总数+1) 这个就是递归的思想
2、Scanner读进来的String不带最后的\n
方法3
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
int length = 0;
char c;
while ('\n' != (c = (char)inputStream.read())) {
length++;
if (c == ' ') {
length = 0;
}
}
System.out.println(length);
}
}
总结:
1、使用字节流读取输入的数据、不同字符字节数是不同的、题目强制要求全为数字所以才可用此方法
2、使用字节流读取输入的数据、空格、回车都会被读进来
3、读取流内容的操作、多字节字符会被拆解了、显示的是单字节字符、这种适合过滤固定的单字节字符
InputStream inputStream // 流的来源
char c; // 临时变量:装苹果的盘子
while ('\n' != (c = (char)inputStream.read())) { // 过滤有用的字节
if (c == ' ') { // c 做某些事
}
}
4、length 重置清零的思想
int length = 0;
while ('\n' != (c = (char)inputStream.read())) {
length++;
if (c == ' ') {
length = 0;
}
}
5、算法不要整理去理解、而是拆分了去理解、当前方法其实就是3和4两个思路拼接起来的算法实现
6、while ('\n' != (c = (char)inputStream.read()))这种思路、取出来值直接判断
6.1、先取出来就没办法使用while循环
6.2、放到循环里就会直接跳过判断、或者各位增加一层判断为\n跳出循环、这样代码不如c = (char)inputStream.read()优美
方法4
方法3的思路、且更好的实现方式
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String str = bf.readLine();
int count = 0;
for (int i = 0; i < str.length(); i++) {
count++;
if (' ' == str.charAt(i)) {
count = 0;
}
}
System.out.println(count);
}
}