Scanner vs. StringTokenizer vs. String.Split [英] Scanner vs. StringTokenizer vs. String.Split

查看:30
本文介绍了Scanner vs. StringTokenizer vs. String.Split的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚了解了 Java 的 Scanner 类,现在我想知道它如何与 StringTokenizer 和 String.Split 进行比较/竞争.我知道 StringTokenizer 和 String.Split 只适用于字符串,那么为什么我要使用字符串扫描器呢?Scanner 只是想成为拆分的一站式购物平台吗?

I just learned about Java's Scanner class and now I'm wondering how it compares/competes with the StringTokenizer and String.Split. I know that the StringTokenizer and String.Split only work on Strings, so why would I want to use the Scanner for a String? Is Scanner just intended to be one-stop-shopping for spliting?

推荐答案

它们本质上是课程的马.

They're essentially horses for courses.

  • Scanner 专为需要解析字符串、提取不同类型数据的情况而设计.它非常灵活,但可以说并没有为您提供最简单的 API,用于简单地获取由特定表达式分隔的字符串数组.
  • String.split()Pattern.split() 为您提供了执行后者的简单语法,但这基本上就是它们所做的全部.如果您想解析生成的字符串,或根据特定标记在中途更改分隔符,它们将无济于事.
  • StringTokenizerString.split() 的限制更多,而且使用起来也有点麻烦.它本质上是为提取由固定子字符串分隔的令牌而设计的.由于这个限制,它的速度大约是 String.split() 的两倍.(参见我的 String.split() 的比较StringTokenizer.)它也早于正则表达式 API,其中 String.split() 是其中的一部分.
  • Scanner is designed for cases where you need to parse a string, pulling out data of different types. It's very flexible, but arguably doesn't give you the simplest API for simply getting an array of strings delimited by a particular expression.
  • String.split() and Pattern.split() give you an easy syntax for doing the latter, but that's essentially all that they do. If you want to parse the resulting strings, or change the delimiter halfway through depending on a particular token, they won't help you with that.
  • StringTokenizer is even more restrictive than String.split(), and also a bit fiddlier to use. It is essentially designed for pulling out tokens delimited by fixed substrings. Because of this restriction, it's about twice as fast as String.split(). (See my comparison of String.split() and StringTokenizer.) It also predates the regular expressions API, of which String.split() is a part.

您会从我的计时中注意到 String.split() 仍然可以在典型机器上标记在几毫秒内数千个字符串.此外,与 StringTokenizer 相比,它的优势在于它以字符串数组的形式提供输出,这通常是您想要的.在大多数情况下,使用 StringTokenizer 提供的 Enumeration 过于语法上的挑剔".从这个角度来说,StringTokenizer现在有点浪费空间,你不妨直接使用String.split().

You'll note from my timings that String.split() can still tokenize thousands of strings in a few milliseconds on a typical machine. In addition, it has the advantage over StringTokenizer that it gives you the output as a string array, which is usually what you want. Using an Enumeration, as provided by StringTokenizer, is too "syntactically fussy" most of the time. From this point of view, StringTokenizer is a bit of a waste of space nowadays, and you may as well just use String.split().

这篇关于Scanner vs. StringTokenizer vs. String.Split的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆