Do we need to solve for nested tags within nested tags?
Please let me know if you thought of a simpler way to go about the solution.
package com.codegym.task.task19.task1918;
/*
Introducing tags
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution {
public static void main(String[] args) {
String fileContents = getFileContents(getFileName());
fileContents = fileContents.replaceAll("\n", "");
fileContents = fileContents.replaceAll("\r", "");
String startingTag = "<" + args[0];
String closingTag = "</" + args[0] + ">";
//split the contents by the starting tag
String[] splitContents = fileContents.split(startingTag);
for (int i = 1; i < splitContents.length; i++) {
//if the line is null, skip it
if (splitContents[i] != null) {
//add the starting tag back in (for sanity)
splitContents[i] = startingTag + splitContents[i];
//if the line doesn't have a closing tag, add the next line
if (!splitContents[i].contains(closingTag)) {
splitContents[i] = splitContents[i] + startingTag + splitContents[i + 1];
splitContents[i + 1] = null;
}
//if there is more than one closing tag in a line, there is a nested tag
if (splitContents[i].indexOf(closingTag) != splitContents[i].lastIndexOf(closingTag)) {
//print out the line with the nested tag per example
System.out.println(splitContents[i]);
//print out the nested tag
int indexOfLastStartingTag = splitContents[i].lastIndexOf(startingTag);
int indexOfFirstClosingTag = splitContents[i].indexOf(closingTag);
System.out.println(splitContents[i].substring(indexOfLastStartingTag, indexOfFirstClosingTag + closingTag.length()));
//if there is not nested tag, print the line
} else {
System.out.println(splitContents[i]);
}
}
}
}
private static String getFileName() {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
return bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String getFileContents(String fileName) {
StringBuilder stringBuilder = new StringBuilder();
try (FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader))
{
while (bufferedReader.ready()) {
stringBuilder.append(bufferedReader.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}