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

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

问题描述

我刚刚学习了Java的Scanner类,现在我想知道它如何与StringTokenizer和String.Split进行比较/竞争。我知道StringTokenizer和String.Split只适用于字符串,那么为什么我要将扫描器用于字符串呢?扫描仪是否只是一次性购买拆分?

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.


  • 扫描程序专为需要解析字符串,提取不同数据的情况而设计类型。它非常灵活,但可以说是没有为您提供最简单的API来简单地获取由特定表达式分隔的字符串数组。

  • String.split() Pattern.split()为后者提供了一个简单的语法,但这基本上就是他们所做的一切。如果你想解析生成的字符串,或者根据特定的标记改变分隔符,它们将无法帮助你。

  • StringTokenizer String.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 提供,在大多数情况下过于语法上挑剔。从这个角度来看, 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天全站免登陆