![](/img/trans.png)
[英]How to compare StringBuilder tokens with multiple java strings?
[英]Effective way to build a list of tokens from multiple strings in Java
我正在尋找一種有效的方法來獲取從多個字符串中提取的字符串標記的列表(例如,使用空格分隔符)。
例:
String s1 = "My mom cook everyday";
String s2 = "I eat everyday";
String s3 = "Am I fat?";
LinkedList<String> tokens = new LinkedList<String>();
//any code to efficiently get the tokens
//final result is tokens make of a list of the following tokens:
//"My", "mom", "cook", "everyday", "I", "eat", "everyday", "Am", "I", "fat?".
現在
LinkedList
是要使用的最有效的收集類(Apache Commons,Guava,它們可以幫忙嗎?)! StringUtils
,但split
方法返回一個數組! 因此,我應該使用for循環從split返回的String對象數組中提取String。 這樣有效嗎:我不知道, split
創建一個數組! Splitter
,但是這篇文章指出StringUtils
在實踐中更好。 Java.util
Scanner
? 似乎沒有分配任何其他數據結構。 是不是 請即使使用其他廣泛使用的庫(例如Guava和Apache Commons) ,也要畫出最有效的Java解決方案。
for (String str : Arrays.asList(s1, s2, s3)) {
Iterables.addAll(tokens, Splitter.on(' ').split(str));
}
就是我會做的方式。 也就是說,在幾乎所有用例中, ArrayList
LinkedList
更可取。 沒有更多數據,我們真的無法確定您是否處於LinkedList
罕見情況之一。
如果您的Strings小且性能不是問題,則可以將split與addAll結合使用,如下所示:
String s1 = "My mom cook everyday";
String s2 = "I eat everyday";
String s3 = "Am I fat?";
List<String> tokens = new ArrayList<String>();
tokens.addAll(Arrays.asList(s1.split("\\s+")));
tokens.addAll(Arrays.asList(s2.split("\\s+")));
tokens.addAll(Arrays.asList(s3.split("\\s+")));
System.out.println(tokens);
但是,如果性能是一個問題,那么這里是一個替代解決方案:
由於這些長文本的獲取方式沒有定義,因此我假設它們出現在InputStream
。 查看此方法是否足以滿足您的需求:
public List<String> readTokens(InputStream is) throws IOException{
Reader reader = new InputStreamReader(is);
List<String> tokens = new ArrayList<String>();
BufferedReader bufferedReader = new BufferedReader(reader);
String line = null;
while((line = bufferedReader.readLine()) != null){
String[] lineTokens = StringUtils.split(line, " ");
for(int i = 0 ; i < lineTokens.length ; i++){
tokens.add(lineTokens[i]);
}
}
return tokens;
}
至於您要在末尾插入的有關ArrayList
和LinkedList
聲明,也許您應該閱讀以下內容
或者只是Arrays.asList((s1 + " " + s2 + " " + s3).split("\\\\s+"))
首先使用分隔符連接字符串(請參閱使用分隔符連接字符串 )。 然后:
LinkedList<String> tokens = new LinkedList<String>();
StringTokenizer st = new StringTokenizer(yourstr); // " " as a default delimiter
while (st.hasMoreTokens()) {
tokens.add(st.nextToken());
}
您是否正在尋找高效或高性能的解決方案(即您的約束/參考績效是什么)?
import java.util.ArrayList;
import java.util.Collections;
public class stringintotoken {
String s="my name is tarun bharti";
ArrayList <String> words=new ArrayList<String>();
public static void main(String[] args)
{
stringintotoken st=new stringintotoken();
st.go();
}
public void go()
{
wordlist();
System.out.println(words);
Collections.sort(words);
System.out.println(words);
}
public void wordlist()
{
String[] tokens=s.split(" ");
for(int i=0;i<tokens.length;i++)
{
words.add(tokens[i]);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.