简体   繁体   English

将字符串分组为字符串数组

[英]Group strings into an array of strings

I got a quick question. 我有一个快速的问题。 I am kinda lazy in the code I write, meaning I want to minimize my typing. 我有点懒于编写代码,这意味着我想尽量减少打字。 I just came across this problem so I am wondering if there is a solution. 我刚遇到这个问题,所以我想知道是否有解决方案。

I have a bunch of strings that I want to loop through. 我有一堆想要循环的字符串。 I was thinking that the best way to do this would be to put them all in an array of strings and loop through array. 我当时认为最好的方法是将它们全部放入一个字符串数组中并遍历数组。

My question: Is there an eclipse shortcut to do this? 我的问题:是否有蚀快捷方式可以做到这一点? Also, is there a better way to loop through a bunch of string variables? 此外,还有更好的方法来遍历一堆字符串变量吗?

Thanks 谢谢

UPDATE: Sorry, I guess I wasn't clear. 更新:对不起,我想我不清楚。 I know how to do a for loop. 我知道如何做一个循环。 Let me post my code: 让我发布我的代码:

private static final String ID = "_id";
private static final String TITLE = "title";
private static final String YEAR = "year";
private static final String DIRECTOR = "director";
private static final String BANNER = "banner_url";
private static final String TRAILER = "trailer_url";

I did this: 我这样做:

private static final String[] labels = {ID, TITLE, YEAR, DIRECTOR, BANNER, TRAILER};

I was looking for a way to loop through it, without putting the strings in an array. 我一直在寻找一种遍历它的方法,而无需将字符串放在数组中。

蚀快捷方式是键入foreach,然后CTRL + SPACE会帮您解决问题。

try this. 尝试这个。

Preferences -> Java -> Editor -> Templates

you should give a keyword for example "helloworld" and define a pattern like this. 您应该给一个关键字,例如“ helloworld”,并定义一个这样的模式。

public static void helloWorld(){
   System.out.println("hello world");
}

apply settings. 应用设置。

and then in your class, write "helloworld" and then CTRL + SPACE, you will see your pattern. 然后在您的课程中,输入“ helloworld”,然后按CTRL + SPACE,您将看到您的模式。

Allow me to rephrase part of your question: "Is there a better way to loop through something other than looping through it?" 请允许我重新表述您的部分问题:“是否有比循环遍历更好的方法?” Think about that. 考虑一下。 If you have to loop, you have to loop. 如果必须循环,则必须循环。

  • Edited out other part since other user gave a better answer. 由于其他用户给出了更好的答案,因此删除了其他部分。

If you type for and Ctrl-Space it'll give you the different iterations available. 如果你输入forCtrl-Space它会给你提供不同的迭代。

To actually create the list the quickest is to use Arrays.asList : 要实际创建列表,最快的方法是使用Arrays.asList

List<String> foos = Arrays.asList("ohai", "kthxbai", "wat"); // Or...
List<String> foos = Arrays.asList(existingStringArray);

I don't know what you have tried so far but for me it's convenient to put them in a List with add and then loop with a "foreach" construct: 我不知道您到目前为止已经尝试过什么,但是对我来说,将它们放入具有add的List中,然后使用“ foreach”构造循环很方便:

List<String> list = new ArrayList<String>();
// add some strings.
for(String s: list) {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM