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);
}