0
I’m trying to erase an interval of content from a StringBuilder
, but when using the method delete()
more than once the program gives error.
Specifically, I’m trying to delete the pseudo-code part of the resolution of some of the questions in a virtual book, leaving only the statement. There is a pattern at the start of pseudocodes, as they begin with Prog and ends with fimprog. Note the example below:
algoritmo 362
Criar um algoritmo que leia dois conjuntos de números inteiros, tendo cada
284 um 10 e 20 elementos, e apresente os elementos comuns aos conjuntos. Lembre-se de que os elementos podem se repetir, mas não podem aparecer repetidos na saída.
prog vetorl10
pseudocógigos...
fimprog
algoritmo 363
Criar um algoritmo que leia vários números inteiros e positivos. A leitura se en-
cerra quando encontrar um número negativo ou quando o vetor ficar completo.
Sabe-se que o vetor possui, no máximo, 10 elementos. Gerar e imprimir um vetor
onde cada elemento é o inverso do correspondente do vetor original.
prog vetorl11
pseudocógigos...
fimprog
algoritmo364...
Code steps:
- The program read a file;
- Puts content in a
StringBuilder
; - The program takes the initial index of the word "Prog" and "fimprog";
- The program calls the delete method and deletes the contents of the defined ranges;
- The program takes the next index of the word "Prog" and "fimprog" again and succeeds, but at the time of deleting the next interval gives error.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.Character.Subset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BuscarPadroes {
public static void main(String[] args) {
String path = "c:\\socket\\Lista_vetor.txt";
String line;
StringBuilder conteudo = new StringBuilder();
int cont = 0;
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
while (br.ready()) {
line = br.readLine();
cont++;
conteudo.append(line + "\n");
}
int start = conteudo.indexOf("prog");
int end = conteudo.indexOf("fimprog");
conteudo.delete(start, end);
start = conteudo.indexOf("prog ");
end = conteudo.indexOf("fimprog");
conteudo.delete(start, end);
} catch (IOException erro) {
System.out.println("Error: " + erro.getMessage());
}
}
}
Gosh, thank you very much. It was exactly the reverse logic that I tried to do, but I couldn’t and I decided to try it this way. Detail, I put two occurrences for testing and for lack of a better understanding of the index. I will read back the documentation of the method.
– Code