今天在做牛客网编程练习题“length of last word”时,当编写实现代码时,使用split()函数对输入的字符串进行按空格符分割,确遇到了”奇葩“的问题,每次只能得到第一个字符串。开始以为是split()函数用错了,查了资料确定无误后,觉得应该是输入的有问题。于是进行了下面的实验:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
String s_next = "";
String s_nextLine = "";
int count_next = 0; // 计数
int count_nextLine = 0; // 计数
Scanner scan = new Scanner(System.in);
System.out.println("请输入第一个字符串:");
s_nextLine = scan.nextLine(); // 此处使用nextLine(),便于对比
System.out.println("请输入第二个字符串:");
s_next = scan.next(); // 第一次使用的next();
scan.close();
String [] split_next = s_next.split("\\s+");
String [] split_nextLine = s_nextLine.split("\\s+");
for(String s : split_next)
System.out.println("子串next: "+ count_next++ +": "+ s + " 长度: " + s.length()+ '\n');
for(String s : split_nextLine)
System.out.println("子串nextLine: "+ count_nextLine++ +": "+ s + " 长度: " + s.length()+ '\n');
}
}
测试结果也验证了我的猜想
总结:
自省,也希望能对大家有所帮助,少走弯路。
-
用 Scanner 实现字符串的输入有两种方法,一种是next(),一种nextLine();
-
next() 一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next() 方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。
-
nextLine()方法的结束符只是Enter键。
简言之,next方法不能得到带空格的字符串,而nextLine()方法返回的是Enter键之前的所有字符,因此出现了上面测试样例的结果。(ps.一定要注意!)
------至所有正在努力奋斗的程序猿们!加油!!
有码走遍天下 无码寸步难行
1024 - 梦想,永不止步!
爱编程 不爱Bug
爱加班 不爱黑眼圈
固执 但不偏执
疯狂 但不疯癫
生活里的菜鸟
工作中的大神
身怀宝藏,一心憧憬星辰大海
追求极致,目标始于高山之巅
一群怀揣好奇,梦想改变世界的孩子
一群追日逐浪,正在改变世界的极客
你们用最美的语言,诠释着科技的力量
你们用极速的创新,引领着时代的变迁
——乐于分享,共同进步,欢迎补充
——Treat Warnings As Errors
——Any comments greatly appreciated
——Talking is cheap, show me the code
——GitHub:https://github.com/selfconzrr