目前我正在创建一个控制台程序,它使用 java Scanner 读取一行非常长的字符串
样本数据更像这样
一行 50000 个整数,用空格分隔,
"11 23 34 103 999 381 ....." until 50000 integer
此数据由用户通过控制台而非文件输入
这是我的代码
System.out.print("Input of integers : ");
Scanner sc = new Scanner(System.in);
long start = System.currentTimeMillis();
String Z = sc.nextLine();
long end = System.currentTimeMillis();
System.out.println("String Z created in "+(end-start)+"ms, Z character length is "+Z.length()+" characters");
然后我执行,结果我得到了这个
String Z created within 49747ms, Z character length is 194539 characters
我的问题是为什么需要很长时间? 有没有更快的方法来读取很长的字符串?
我试过缓冲阅读器,但差别不大..
String Z created within 41881ms, Z character length is 194539 characters
最佳答案
看起来扫描仪使用正则表达式来匹配行尾 - 这可能会导致效率低下,尤其是当您将正则表达式与 200k 长度的字符串进行匹配时。
使用的模式实际上是 .*(\r\n|[\n\r\u2028\u2029\u0085])|.+$
关于java - 使用 Java Scanner 从控制台读取很长的字符串需要时间吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8228029/