Separate String in Java Character

Asked

Viewed 130 times

-2

Guys, I’m trying to separate a string into characters...for example, if I type "race" I want it to come out "c o r i d a", but I’m not getting it, where I’m going wrong?

import javax.swing.JOptionPane;
public class mensagem {
    public static void main(String[] args) {

            String mensagem;
            mensagem = JOptionPane.showInputDialog("Digite sua mensagem a ser separada:");
            
            String vetor[] = {mensagem};
            
            for(int i = 0; i<=vetor.length-1; i++) {
                JOptionPane.showMessageDialog(null, "Mensagem divida por caractere: " 
            + vetor[i]);
                
            }   
    }
}
  • 1

    Do not forget to accept any of the answers if they have answered you

2 answers

2

Could try iterating with a class instance string. And iterate the characters of this String with the method charAt.

Follow an example:

public static void main(String args[]) {
        String vetor = "corrida";
        char c;
        for(int i = 0; i<=vetor.length()-1; i++) {
            c = vetor.charAt(i);
            System.out.println(c);
            
        }
}

To try to solve your specific problem you could mount the message you want to display on optionPane using an auxiliary variable.

In my example I changed the type of String for StringBuilder for reasons of efficiency. When using the Stringbuilder class we must interact with the methods exposed by the Stringbuilder class, in this case to concatenate just use the method append().

Example:

public static void main (String[] args) {
        final String separador = System.getProperty("line.separator");
        String vetor = "corrida";
        char c;
        StringBuilder tmpmsg = new StringBuilder();
        for(int i = 0; i<=vetor.length()-1; i++) {
            c = vetor.charAt(i);
            //tmpmsg.append(c).append(separador); #para utilizar quebra de linha
            tmpmsg.append(c).append(' '); // #para utilizar espaços
            
        }
        System.out.println(tmpmsg);
        // agora só precisa criar 1 instância do jOptionPane (não é necessário fazer um for)
        JOptionPane.showMessageDialog(null, "Mensagem divida por caractere: " + tmpmsg);
}

In this example I am using the method System.getProperties which is a helper function to facilitate access to a property of the operating system where the JVM is running. In this case I am wanting to get the line separator property (line.separator). For a complete list of which properties can be accessed just go to documentação do método getProperties.

There are some things to improve in this code such as modularizing actions.

  • 1

    @Augustovasques, updated, I did not find a good reference (in English) to explain why concatenating string is inefficient, I can understand its explanation, but I would like something more didactic, here in sopt also I did not find a content that has good references. Maybe you didn’t look for the right terms.

  • That’s all we need System.getProperty("line.separator"); she wants spaces not new lines. The code is well optimized. When concatenating strings the operation is O(n) because string is immutable and environment creates a new string with each concatenation, Stringbuilder’s append is constant-time temcomplexity O(1).

  • PS: If there are many characters, it is still possible to optimize https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#%3Cinit%3E(int)

  • 1

    On the efficiency of concatenating strings into a loop: https://answall.com/q/71517/112052 cc @Augustovasques - remember that from Java 9 some details have changed: https://www.baeldung.com/java-string-concatenation-invokedynamicinvoke-dynamic

  • 1

    @hkotsubo I’m sleepy, I read only the beginning, I’m sorry. it was written pretty big A new Stringbuilder will be created at each iteration (with the initial str value) and at the end of each iteration, there will be concatenation with the initial String (actually Stringbuilder with str initial value). So, you should create Stringbuilder ourselves only when we are concatenating Strings into loops.

2

Your first debt String using the method split:

String vetor[] = mensagem.split("");

What happens is that you are showing each character separately, showing a message for each. If you are using a version from Java 8, you can replace the loop for:

OptionPane.showMessageDialog(null, "Mensagem divida por caractere: " + String.join(" ", vetor));

Browser other questions tagged

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