David_Garcia
David_Garcia

Reputation: 654

StringTokenizer and Split don't work

I need a hand with a project that I have and I'm totally stuck here.

I try with SringTokenizer:

StringTokenizer st = new StringTokenizer(auxiliar2, "+");
while (st.hasMoreElements()) {
    try{
        Textos seleccion = new Textos();
        seleccion.setBook(st.nextElement().toString());
        seleccion.setSection(st.nextElement().toString());
        seleccion.setMemorization(st.nextElement().toString());
        texto.add(seleccion);
    }finally{           
    }
}

In the StringTokenizer make me the first loop correct, but when it does the second it didn't find the next element of seleccion.setMemorization(st.nextElement().toString()); And then I read that split works better then I used it.

String[] tokens = auxiliar2.split("+");
for (int x = 0; x < tokens.length-1 ; x++ ){
    Textos seleccion = new Textos();
    seleccion.setBook(tokens[x].toString());
    seleccion.setSection(tokens[x+1].toString());
    seleccion.setMemorization(tokens[x+2].toString());
    texto.add(seleccion);
    x = x+2;
}

But in this way it didn't work either. Here I tried, but I don't know why gives me only the chars of the string.

Please can you help me? Thanks!!!!

Upvotes: 0

Views: 90

Answers (1)

rgettman
rgettman

Reputation: 178263

The split method takes a regular expression as an argument, and + has special meaning within regular expressions.

Escape the + with a backslash \, then escape the backslash itself for Java.

String[] tokens = auxiliar2.split("\\+");

Upvotes: 4

Related Questions