|
1 | | -/* |
2 | 1 |
|
3 | | -Since this exercise has a difficulty of > 4 it doesn't come |
4 | | -with any starter implementation. |
5 | | -This is so that you get to practice creating classes and methods |
6 | | -which is an important part of programming in Java. |
| 2 | + String parse(String markdown) { |
| 3 | + String[] lines = markdown.split("\n"); |
| 4 | + String result = ""; |
| 5 | + boolean activeList = false; |
7 | 6 |
|
8 | | -Please remove this comment when submitting your solution. |
| 7 | + for (int i = 0; i < lines.length; i++) { |
9 | 8 |
|
10 | | -*/ |
| 9 | + String theLine = parseHeader(lines[i]); |
| 10 | + |
| 11 | + if (theLine == null) { |
| 12 | + theLine = parseListItem(lines[i]); |
| 13 | + } |
| 14 | + |
| 15 | + if (theLine == null) |
| 16 | + { |
| 17 | + theLine = parseParagraph(lines[i]); |
| 18 | + } |
| 19 | + |
| 20 | + if (theLine.matches("(<li>).*") && !theLine.matches("(<h).*") && !theLine.matches("(<p>).*") && !activeList) { |
| 21 | + activeList = true; |
| 22 | + result = result + "<ul>"; |
| 23 | + result = result + theLine; |
| 24 | + } |
| 25 | + |
| 26 | + else if (!theLine.matches("(<li>).*") && activeList) { |
| 27 | + activeList = false; |
| 28 | + result = result + "</ul>"; |
| 29 | + result = result + theLine; |
| 30 | + } else { |
| 31 | + result = result + theLine; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + if (activeList) { |
| 36 | + result = result + "</ul>"; |
| 37 | + } |
| 38 | + |
| 39 | + return result; |
| 40 | + } |
| 41 | + |
| 42 | + private String parseHeader(String markdown) { |
| 43 | + int count = 0; |
| 44 | + |
| 45 | + for (int i = 0; i < markdown.length() && markdown.charAt(i) == '#'; i++) |
| 46 | + { |
| 47 | + count++; |
| 48 | + } |
| 49 | + |
| 50 | + if (count == 0) { return null; } |
| 51 | + |
| 52 | + return "<h" + Integer.toString(count) + ">" + markdown.substring(count + 1) + "</h" + Integer.toString(count)+ ">"; |
| 53 | + } |
| 54 | + |
| 55 | + private String parseListItem(String markdown) { |
| 56 | + if (markdown.startsWith("*")) { |
| 57 | + String skipAsterisk = markdown.substring(2); |
| 58 | + String listItemString = parseSomeSymbols(skipAsterisk); |
| 59 | + return "<li>" + listItemString + "</li>"; |
| 60 | + } |
| 61 | + |
| 62 | + return null; |
| 63 | + } |
| 64 | + |
| 65 | + private String parseParagraph(String markdown) { |
| 66 | + return "<p>" + parseSomeSymbols(markdown) + "</p>"; |
| 67 | + } |
| 68 | + |
| 69 | + private String parseSomeSymbols(String markdown) { |
| 70 | + |
| 71 | + String lookingFor = "__(.+)__"; |
| 72 | + String update = "<strong>$1</strong>"; |
| 73 | + String workingOn = markdown.replaceAll(lookingFor, update); |
| 74 | + |
| 75 | + lookingFor = "_(.+)_"; |
| 76 | + update = "<em>$1</em>"; |
| 77 | + return workingOn.replaceAll(lookingFor, update); |
| 78 | + } |
| 79 | +} |
0 commit comments