In my Android project I have a plain text in put from a edittext field like below,
1. Who is superhero?
a) Spiderman
b) Batman
c) Ironman
& etc, multiple questions and answers; this plain text needs to be parsed and each value i.e; questions, each individual answer choices needs to be updated in to individual row cells of a csv file like below,
Any help or inputs on how to achieve this would be much appreciated.
Simply split your text into lines, every 4 lines you have a question. Simply parse each line and make a csv line by separating the values with a comma
private String parse(String text) {
// create the header line
StringBuilder csv = new StringBuilder("Sl No,Question,Option A,Option B,Option C");
// get every line in an array
String[] array = text.split("\n");
// for every 4 lines
for(int i=0; i<array.length; i = i+4) {
String question = array[i];
String optionA = array[i+1];
String optionB = array[i+2];
String optionC = array[i+3];
String questionNo = question.substring(0, question.indexOf(".")).trim();
String questionText = question.substring(question.indexOf(".")+1).trim();
String optionAText = optionA.substring(optionA.indexOf(" ")).trim();
String optionBText = optionB.substring(optionB.indexOf(" ")).trim();
String optionCText = optionC.substring(optionC.indexOf(" ")).trim();
// build the corresponding csv line
String csvLine = questionNo+","+questionText+","+optionAText+","+optionBText+","+optionCText;
csv.append("\n");
csv.append(csvLine);
}
return csv.toString();
}
Assuming this input text:
String text =
"1. Who is superhero?\n" +
"a) Spiderman\n" +
"b) Batman\n" +
"c) Ironman\n" +
"2. question 2\n" +
"a) answer 1\n" +
"b) answer 2\n" +
"c) answer 3";
String csv = parse(text);
it returns the following String
Sl No,Question,Option A,Option B,Option C
1,Who is superhero?,Spiderman,Batman,Ironman
2,question 2,answer 1,answer 2,answer 3