我有这个: 示例输入:
* First item
* Second item
* Subitem 1
* sub-subitem!
* Subitem 3
* Third item
示例输出:
<ul>
<li>First item</li>
<li>Second item
<ul>
<li>Subitem 1
<ul>
<li>sub-subitem!</li>
</ul>
</li>
<li>Subitem 3</li>
</ul>
</li>
<li>Third item</li>
</ul>
我创建了一个 Java 类,它将每个字符串行发送到一个字符数组,并且我单独处理每个字符。我的问题是何时关闭标签有什么想法吗?
这是我的代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TextToHtml {
StringBuilder itemName = new StringBuilder();
String sCurrentLine;
int usingUlTAG=0;
public TextToHtml(){
BufferedReader br = null;
try {
boolean closeLItag=false;
br = new BufferedReader(new FileReader("NestedText.txt"));
System.out.println("<ul>");
while ((sCurrentLine = br.readLine()) != null) {
char[] item = sCurrentLine.toCharArray();
for(int i=0; i<item.length;i++){
if(item[i]!='*' && item[i]!='\n' && item[i]!='\t'){
itemName.append(item[i]);
continue;
}
if(item[i]=='*'){
itemName.append("<li>");
closeLItag=true;
}
else if(item[i]=='\t'){
if(item[i+1]=='*'){
if(usingUlTAG<1)
itemName.append("\t<ul>\n\t\t");
itemName.append("\t\n\t\t");
usingUlTAG= 1;
continue;
}
if(item[i+1]=='\t'){
itemName.append("\t\t<ul>\n\n\t\t");
usingUlTAG=2;
continue;
}
}
}
if(closeLItag){
itemName.append("</li>\n");
}
}
System.out.println(itemName+"/ul>");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new TextToHtml();
}
}