How to break (split) strings and put result in separate variables? [closed]

0
public class Teste30 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String teste = "Isso funciona mesmo, ok?";
        String [] vetor = teste.split(" ");

        String aqui = null;
        String ali = null;
        String acola;
        String there;

        aqui = vetor[0];
        ali = vetor[1];
        acola = vetor[3];
            there = vetor[4];
        }
        for(String nome : vetor){
            System.out.println(nome);

        }
    }

I would like to know if you have a rather non-existent way of including these% s of matches in the variables that hold this value.

    
asked by anonymous 18.12.2016 / 04:44

1 answer

0

It's all about simplicity.

In this example the least legible way is not to do this assignment for these variables. They are not being used and even if they are used in a code continuation, for what? Use the vector variables themselves.

If you have to create the same variables, declare the attribute at once.

Variables are memory storage locations with a name, nothing more. Why store a value somewhere with a name? Usually because you need to use it more than once. Or you need to do several steps with that value that can not be put together. It may also be when you are doing something very complex and you want to document it better, but this is less common.

Why create unnecessary variables? Whenever you can not explain why a variable exists, delete it. This basic "rule" already helps. Of course the person can still give meaningless explanations.

Simplified code that does the same thing (the code did not compile in written form):

class Teste30 {
    public static void main(String[] args) {
        for (String nome : "Isso funciona mesmo, ok?".split(" ")) {
            System.out.println(nome);
        }
    }
}

See running on ideone and on CodingGround .

But if you still want to create these loose variables for later use:

class Teste30 {
    public static void main(String[] args) {
        String teste = "Isso funciona mesmo, ok?";
        String[] vetor = teste.split(" ");
        String aqui = vetor[0];
        String ali = vetor[1];
        String acola = vetor[3];
        String there = vetor[4];
        for (String nome : vetor) {
            System.out.println(nome);
        }
    }
}

See working on ideone and on CodingGround .

    
18.12.2016 / 10:40