How do I separate a line of text and store it in a vector in Java?

1

I have a text file, which is read and stored in a variable linea , then I separate the content of the line with linea.split(); . How do I make the content stored in a vector, being already separated?

For example:

4 1 H 6 O 3 H 5 O - I separate this line with linea.split(); , how do I make each piece of that line, stored in a vector?

Update: I would like the vector to be [4, 1, H, 6, O, 3, H, 5, O]

    
asked by jeison0323 09.09.2016 в 17:05
source

2 answers

3

String.split already returns an array of Strings. And you can use the regular expression \s+ to also consider when there is more than one space between the words or separated by tabs.

To convert it into a vector of strings you can use a Vector constructor and method static asList of Arrays .

String linea = "4 1 H 6 O 3 H 5 O";
String[] palabras = linea.split("\s+");
Vector<String> vectorPalabras = new Vector(Arrays.asList(palabras));

Although, in general, it is preferable to treat the collection through an interface such as List as this makes the code more generic, reusable and easy to refactor if necessary. And it is discouraged to use Vector (link in English) .

List<String> vectorPalabras = Arrays.asList(palabras);
    
answered by 09.09.2016 в 17:31
2
  

I would like the vector to be [4, 1, H, 6, O, 3, H, 5, O]

There are several ways to do this, using RegEx by split() for example, using Pattern.compile(" ") as RegEx:

 String linea = "4 1 H 6 O 3 H 5 O";          
 Pattern SPACE = Pattern.compile(" ");
 String[] letras = SPACE.split(linea); 
 //Al generar un Array convertimos a vector
 Vector<String> vectorLetras = new Vector(Arrays.asList(letras));

This is another way using the RegEx "\s+" :

String linea = "4 1 H 6 O 3 H 5 O";
String[] letras = linea.split("\s+");
//Al generar un Array convertimos a vector
Vector<String> vectorLetras = new Vector(Arrays.asList(letras));

Even using StringTokenizer

String linea = "4 1 H 6 O 3 H 5 O";            
StringTokenizer tokens = new StringTokenizer(linea, " ");
String[] letras = new String[tokens.countTokens()];
int index = 0;
while(tokens.hasMoreTokens()){
   letras[index] = tokens.nextToken();
   ++index;
}

//Al generar un Array convertimos a vector
Vector<String> vectorLetras = new Vector(Arrays.asList(letras));

In the 3 cases you would get your vector of the form:

[4, 1, H, 6, O, 3, H, 5, O]

You can check it by printing the values saved in the vector by:

 String [] s = vectorLetras.toArray(new String[vectorLetras.size()]);
  for(String elemento: s){
     System.out.println("letra: " + elemento);
  }
    
answered by 18.04.2017 в 00:21