Ok it's time for ask for help. After few hours of work I have this. I think something wrong with my trying create algorithm to solve situation when this tag is a little mess. (line 68-74).
Maybe it possible way when I could repair this program. Am I long for good solution? I feel I'm close to do this.
package com.codegym.task.task19.task1918;
/*
Introducing tags
/home/mati/temporary/file4.txt
args[0] "span"
<span>girl</span>
<span xml:lang="en" lang="en"<span>girl</span><span>Leela Turanga</span></span>
<span xml:lang="en" lang="en"><b><span>Leela Turanga</span></b></span>
<span>picza<span>Leela Turanga</span></span>
<span>Super</span>
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
reader.close();
String parameter = args[0];
String openTag = "<" + parameter; // <span
String closeTag = "</" + parameter; // </span
try (BufferedReader reader1 = new BufferedReader(new FileReader(fileName))) {
while (reader1.ready()) {
// Read one line and replace original tags on new ONE character sign
String line = reader1.readLine();
// checking counter of tags
String omega = "Ω";
String omegaReplace = line.replaceAll(closeTag, omega);
char[] lineToChar = omegaReplace.toCharArray();
char[] omegaArray = omega.toCharArray();
char omegaChar = omegaArray[0];
int counterOfTagsPerLine = 0;
for (char c : lineToChar) {
if (c == omegaChar)
counterOfTagsPerLine++;
}
// create two list for write each tag open and close index
ArrayList<Integer> indexesOfOpen = new ArrayList<>();
ArrayList<Integer> indexesOfClose = new ArrayList<>();
// now do it
int newIndex = 0;
int newIndextLast = 0;
for (int i = 0; i < counterOfTagsPerLine; i++) {
int index = line.indexOf(openTag, newIndex);
int indexLast = line.indexOf(closeTag, newIndextLast);
indexesOfOpen.add(index);
indexesOfClose.add(indexLast);
newIndex = index + 1;
newIndextLast = indexLast + 1;
}
// when situation is bad like in example for Guadalupe:
// <span xml:lang="en" lang="en"<span>girl</span><span>Leela Turanga</span></span>
// we need change order
for (int i = 0; i < indexesOfOpen.size(); i++) {
if (indexesOfOpen.get(indexesOfOpen.size() - 1 - i) > indexesOfClose.get(i)) {
int temporary = indexesOfClose.get(i + 1);
indexesOfClose.add(i + 1, indexesOfClose.get(i));
indexesOfClose.add(i, temporary);
indexesOfClose.remove(i + 2);
indexesOfClose.remove(i + 2);
}
}
// for (int i : indexesOfClose) {
// System.out.print(i + " ");
// }
// System.out.println();
// Finally we can print what we get
for (int i = 0, j = counterOfTagsPerLine - 1; i < counterOfTagsPerLine; i++, j--) {
System.out.println(line.substring(indexesOfOpen.get(i), indexesOfClose.get(j) + closeTag.length() + 1));
}
}
}
}
}