[英]Split line from a file into different substrings
I need help in order to split some individual lines into different substrings with the help of IndexOf. 我需要帮助,以便在IndexOf的帮助下将一些单独的行分成不同的子串。
The substrings are separated with *, for example: 子串用*分隔,例如:
Question*Answer*AnswerA*AnswerB*CorrectAwnser
问*答案* AnswerA * AnswerB * CorrectAwnser
How can I split the string in order to get Answer, AnswerA, AnswerB, and CorrectAnswer? 如何分割字符串以获得Answer,AnswerA,AnswerB和CorrectAnswer?
Here is part of my code. 这是我的代码的一部分。 What could I do after
getQuestion()
with getAnserA, getAnserB and getCorrectAnswer 使用getAnserA,getAnserB和getCorrectAnswer在
getQuestion()
之后我该怎么办?
try {
InputStream is = context.getAssets().open(questionFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Skips lines
for (int i = 0; i< questionCount; i++) {
reader.readLine();
}
question = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
public String getQuestion() {
return question.substring(0, question.indexOf("*"));
}
Use a StringTokenizer to split a string to n number of strings. 使用StringTokenizer将字符串拆分为n个字符串。 you need to pass the delimiters.
你需要通过分隔符。
for example 例如
String questiongString = "Question1*Question2*Question3";
StringTokenizer splitter = new StringTokenizer(questionString, "*");
while (splitter.hasMoreTokens()) {
String question = splitter.nextToken();
}
You don't need indexOf, String has a useful split method: 你不需要indexOf,String有一个有用的split方法:
String[] parts = question.split("\\*");
String q = parts[0];
String answer = parts[1];
String answerA = parts[2];
String answerB = parts[3];
String correctAnswer = parts[4];
int indexOfFirstStar = question.indexOf('*');
int indexOfSecondStar = question.indexOf('*', indexOfFirstStar + 1);
int indexOfThirdStar = question.indexOf('*', indexOfSecondStar + 1);
...
Once you have all the indices, you just need to use substring. 获得所有索引后,只需使用子字符串即可。 Read the String javadoc .
阅读String javadoc 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.