giacomotb
giacomotb

Reputation: 607

Run-time error in .split("|")

I'm using that method in that line:

f.getCmbAttori().getSelectedItem().toString().split("|")

with an input like "13|Il Signore degli Anelli" and insted of return:

f.getCmbAttori().getSelectedItem().toString().split("|")[0] = "13"
f.getCmbAttori().getSelectedItem().toString().split("|")[1] = "Il Signore degli Anelli"

It returns an array where every character is alone, like this:

    f.getCmbAttori().getSelectedItem().toString().split("|")[0] = ""
    f.getCmbAttori().getSelectedItem().toString().split("|")[1] = "1"
    f.getCmbAttori().getSelectedItem().toString().split("|")[2] = "3"
    f.getCmbAttori().getSelectedItem().toString().split("|")[3] = "|"
    f.getCmbAttori().getSelectedItem().toString().split("|")[4] = "I"
    f.getCmbAttori().getSelectedItem().toString().split("|")[5] = "l"
[...]

    f.getCmbAttori().getSelectedItem().toString().split("|")[25] = "l"
    f.getCmbAttori().getSelectedItem().toString().split("|")[26] = "i"

How can be possible that? I'm wrinting this method in a wrong way? Here a piece of code where I use that:

PreparedStatement stmSql = null;
                 int risultato = 0;                  
                 stmSql = f.conn.prepareStatement("insert into recita (CodAttore, CodFilm) values (?, ?)");
                 stmSql.setInt(1, Integer.parseInt(f.getCmbAttori().getSelectedItem().toString().split("|")[1]));
                 stmSql.setInt(2, Integer.parseInt(f.getCmbFilmRecita().getSelectedItem().toString().split("|")[1]));
                 risultato = stmSql.executeUpdate();

Upvotes: 1

Views: 537

Answers (3)

Rakesh KR
Rakesh KR

Reputation: 6527

Try split("\\|");

OR You can use

split(Pattern.quote("|"));

java.lang.String.split splits on regular expressions.

Twelve characters have special meanings in regular expressions: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), the opening square bracket [, and the opening curly brace {.

These special characters are often called "metacharacters".

For More

Upvotes: 1

M21B8
M21B8

Reputation: 1887

The String.split function takes a regex, try using this:

split("\\|")

this will make it split on a literal |

Upvotes: 5

rzymek
rzymek

Reputation: 9281

Generally if you want to split by fixed string (instead of a regex) use quote:

.split(Pattern.quote("|"))

Upvotes: 2

Related Questions