Separate chain with split and store the data only in necessary variables

0

I have the following code:

String cadena=JTextField.getText();
String[] split=cadena.split("\s");
String p1=split[0];
String p2=split[1];
String p3=split[2];

As you can see, the code separates the string into 3 words that are stored in the variables p1, p2, p3.

The problem is that it will only work if I have written 3 words in the JTextField , if I write only 2 words or 4 words will send me an error.

I would like that if I write (in the JTextField ) a string with X number of words in it, these words are stored one by one in a different variable . So I am not limited to writing only 3 words, but all those I need, including if I write only one word.

    
asked by Ian Stucchi 10.12.2017 в 05:23
source

1 answer

0

Can not do with repeated String palabraN = split[x];

You should use a lista simplemente enlazada , or ArrayList<> that are practically the same.

It would be something like:

String cadena=JTextField.getText();

String[ ]split=cadena.split("\s");

ArrayList<String> pal = new ArrayList<>();

for(int i = 0; i < split.length; i++){ // no recuerdo si es length o length()
    pal.add(split[i]);
}

It is up to you to convert it to something more efficient as a foreach , look for examples of vector , arraylist and list

    
answered by 10.12.2017 / 08:10
source