How to concatenate strings from a 3-in-3 vector in Java?

Asked

Viewed 138 times

-1

I need to concatenate the elements of a 3-in-3 vector.

Follow the sample of what I need:

package ex;

public class prog {

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

        String[] vetor = {"aaa", "aaa", "aaa", "bbb", "bbb", "bbb", "ccc", "ccc", "ccc", "ddd", "ddd", "ddd"};

String[] novo_vetor; // vetor que terá as strings "aaaaaaaaa", "bbbbbbbbb", "ccccccccc", "ddddddddd");
    }

}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

3

You can do it like this:

class HelloWorld {
    public static void main(String[] args) {
        String[] vetor = {"aaa", "aaa", "aaa", "bbb", "bbb", "bbb", "ccc", "ccc", "ccc", "ddd", "ddd", "ddd"};
        String[] novoVetor = new String[vetor.length / 3];
        for (int i = 0; i < vetor.length; i += 3) novoVetor[i / 3] = vetor[i] + vetor[i + 1] + vetor[i + 2];
        for (String item : novoVetor) System.out.println(item);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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