Encryption using java stacks

Asked

Viewed 544 times

5

In an encrypted message using stack to invert each word of a String and using the chatAt(int) to pick up specific characters from it, I had the following problem, when placing a character on the stack, you cannot use primitive types as parameterized type.

How to solve by creating a stack of the type wrapper Character instead of declaring a Stack of char implementing message encryption and encryption?

As an example the text "A confidential message" encrypted should be "Amu megasnem laicnedifnoc".

  • 1

    what is your doubt?

  • How I’m gonna stack the string and unstack encrypted. @Dorivalzanetto

  • 1

    I edited your question in case it didn’t fit your needs, disregard it, but keep your content organized so it’s easy to understand and make your question clear, for example, "How do I use the stack this way?".

1 answer

5


If you don’t necessarily need to use stacks and use Java 8, everything can be done very 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 cannot use Java 8, you can still do so:

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, can retrieve the character array 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 battery for whatever reason, you can do so:

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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.