Cryptography using piles in java

5

In an encrypted message using Stack to invert each word of a String and using chatAt (int) to get characters specific to it, I had the following problem, when if you put a character on the stack, you can not use primitive types as a parameterized type.

How do I solve by creating a stack of type wrapper Character instead of declaring a stack of char implementing cryptography and message encryption?

As an example the text "An encrypted confidential message" should be "amu megasnem laicnedifnoc".

    
asked by anonymous 13.11.2015 / 00:04

1 answer

5

If you do not necessarily need to use stacks and use Java 8, everything can be done quite directly like this:

String texto = "Uma mensagem confidencial";
String reverso = Arrays.stream(texto.split("\s")) //quebra string por espaços
        .map(s -> new StringBuilder(s).reverse().toString()) //inverte cada palavra
        .collect(Collectors.joining(" ")); //junto tudo de novo

If you can not use Java 8, you can still do this:

String texto = "Uma mensagem confidencial";
String[] palavras = texto.split("\s");
StringBuilder sb = new StringBuilder();
for (String palavra : palavras) {
    sb.append(new StringBuilder(palavra).reverse());
    sb.append(" ");
}
String reverso = sb.toString();

If you prefer not to use the ready method of StringBuilder , you can retrieve the character vector of each word individually:

String texto = "Uma mensagem confidencial";
String[] palavras = texto.split("\s");
StringBuilder sb = new StringBuilder();
for (String palavra : palavras) {
    char[] letras = palavra.toCharArray();
    for (int i = letras.length - 1; i >= 0; i--) {
        sb.append(letras[i]);
    }
    sb.append(" ");
}
String reverso = sb.toString();

Anyway, if you still prefer to use a stack for whatever reason, you can do this:

String texto = "Uma mensagem confidencial";
char[] letras = texto.toCharArray(); //vetor de caracteres
StringBuilder sb = new StringBuilder(letras.length); //buffer contendo resultado
Deque<Character> pilha = new ArrayDeque<>(letras.length); //pilha
for (char letra : letras) {
    if (Character.isWhitespace(letra)) { //se for espaço
        while (!pilha.isEmpty()) sb.append(pilha.pop()); //esvazia pilha
        pilha.clear(); //limpa pilha
        sb.append(letra); //mantém o espaço
    } else {
        pilha.push(letra);
    }
}
while (!pilha.isEmpty()) sb.append(pilha.pop()); //esvazia resto da pilha
String reverso = sb.toString();
    
13.11.2015 / 02:30