我知道使用split函数拆分句子的正常方法,但问题是您需要声明需要多少变量, 示例:格斗,动作,冒险,赛车,角色扮演
String[] GameGenreCodeSeparated = GameGenreCodeRAW.split(",");
listGameGenre.add(GameGenreCodeSeparated[0]);
listGameGenre.add(GameGenreCodeSeparated[1]);
listGameGenre.add(GameGenreCodeSeparated[2]);
如何为每个","符号添加一个列表,以便列表可以动态包含该句子中的 5 个对象,有什么解决方案吗?
您可能希望遍历数组。像下面这样的东西应该可以工作。
String[] GameGenreCodeSeparated = GameGenreCodeRAW.split(",");
for (String GameGenre: GameGenreCodeSeparated ) {
listGameGenre.add(GameGenre);
}
使用内置方法Arrays.asList(GameGenreCodeRAW.split(","))
以避免手动添加。
@Sungakki 您应该检查哪种方法更好,在这种情况下,Arrays.asList(GameGenreCodeRAW.split(","))
看起来更好的方法,将来也可以为您提供帮助。 原因是 Arrays.asList(( 是处理数组的标准实用程序方法。编写自定义 for(( 循环在这里毫无意义。
如果您难以理解它在做什么,以下是有关此内容的更多详细信息。
下面介绍了如何在代码中使用它。
listGameGenre = Arrays.asList(GameGenreCodeRAW.split(","((;
Arrays.asList()
只是返回一个固定大小的列表,在我们的例子中,它是由指定的数组支持的,它是GameGenreCodeRAW。
以下是Arrays.asList()
官方文档的官方文档。
我希望你理解我的意思。
最好创建一个新的数组或数组列表,因为尝试拆分字符串但不在其他任何地方存储任何数据会很混乱。 我认为应该是这样的:
import java.util.ArrayList;
public class test
{
public static void split(String raw){
ArrayList <String> GameGenreCodeSeparated= new ArrayList<String>();
int splits=0;//how man times have the sentence been splited
int previousSplited=0;//index of the prevoius comma
for(int i=0;i<raw.length();i++){
if(raw.charAt(i)==','){//when comma occurs
if(previousSplited==0){//if this is the first comma
GameGenreCodeSeparated.add(raw.substring(0,i));//add the splited string to the list
previousSplited=i;//record the place where splited
}
else{
GameGenreCodeSeparated.add(raw.substring(previousSplited+1,i));//add the splited string to the list
previousSplited=i;//record the place where splited
}
}
else if (i==raw.length()-1){//if this is the end of the string
GameGenreCodeSeparated.add(raw.substring(previousSplited+1,i));//add the splited string to the list
previousSplited=i;//record the place where splited
}
}
System.out.println(GameGenreCodeSeparated);//print out results;
}
}
希望这有帮助!
String text = "In addition, Androids could multitask, whereas iPhones could not at that time. By 2011, Android outsold every other smartphone";
String[] textSeparated = text.split(",");
String first=textSeparated[0];
String second=textSeparated[1];
String Third=textSeparated[2];
String Fourth=textSeparated[3];