user82779
user82779

Reputation: 65

Strings turn out blank when split

String data = line.split(":")[1];

String location = data.split("|")[0];
String type = data.split("|")[1];

System.out.println("D: " + type);
int x = Integer.parseInt(location.split("-")[0]);
int y = Integer.parseInt(location.split("-")[1]);

int t = Integer.parseInt(type);

The original strings that are inputed into this parser are formated like "DATA:3,3|1". I'm trying to parse it to the format of "DATA:x,y|t". The problem is that the string location is blank when it's split off from the string data. Why?

Upvotes: 0

Views: 61

Answers (2)

RobertS
RobertS

Reputation: 135

As sp00m said you can use :

split("\\|") or split("[|]")

Or you can use

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

To test beforehand if the string contains a character, just use

String#contains()

if (string.contains("\\|")) { 
    // Split it. 
} 
else {
  throw new IllegalArgumentException("String " + string + " does not contain |"); 
 }

Upvotes: 0

sp00m
sp00m

Reputation: 48817

Because split() takes a regex as parameter, and | is actually a regex special char (and also a syntaxically valid regex as is, which explains that no error is thrown).

You need to escape it: either split("\\|"), or split("[|]").

Upvotes: 8

Related Questions