Java的:找到第10个字的字符串。什么是最有效的算法? [英] Java: Find the first 10 words in a string. What is the most efficient algorithm?

查看:118
本文介绍了Java的:找到第10个字的字符串。什么是最有效的算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试写一些code以检索第10个字的字符串。

I am trying to write some code which retrieves the first 10 words of a string.

最好的算法,我可以想像是空间分割字符串,在第一个10个元素。然而,这不是BERY高效为串可能是很长的。

The best algorithm I can imagine is to split the string by space and take the first 10 elements. However, this is not bery efficient as the string could be very long.

有没有更好的算法在Java中,能做到这一点?

Is there any better algorithm in Java that can achieve this?

非常感谢。

推荐答案

您可以使用<一个href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split%28java.lang.String,%20int%29"><$c$c>String.split(String正则表达式,INT限制) 具有特定的限制 - 不调用正则表达式规则的详细然后11倍

You can use String.split(String regex,int limit) with a specific limit - don't invoke the regex rule more then 11 times.

这将创建一个的String [] 对象,用10第一要素是分开的话,最后一个元素包含其中,规则上还没有被选中的话[所以它不会分割字符串的其余]

It will create a String[] object, with 10 first elements are seperate words, and the last element contain words where the rule was not checked on yet [so it will not split the rest of the string]

这篇关于Java的:找到第10个字的字符串。什么是最有效的算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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