I am trying to split a string of words and each word is separated by a " . " I don't know what i'm doing wrong:
@Override
protected void onPostExecute(String result) {
result = "order . war harmony . concord";
result = result.replace("(noun)", "");
result = result.replace("(antonym)", "");
result = result.replace(":", "");
result = result.replace("|", " . ");
String[] separated = result.split(".");
tv.setText(result + ": " + separated.length);
super.onPostExecute(result);
}
Yet separated.length is always 0!
The period (.) needs to be escaped, because String#split
uses a regex. In regex an unescaped period means any character:
String[] separated = result.split("\\.");
Split method in java takes regex parameter, so be careful that in regex the character "." means any character, so you need to deal with it as a special character.
Hence your code might be as the following:
@Override
protected void onPostExecute(String result) {
result = "order . war harmony . concord";
result = result.replace("(noun)", "");
result = result.replace("(antonym)", "");
result = result.replace(":", "");
result = result.replace("|", " . ");
// changed the splitting character "." to be regex "\\."
String[] separated = result.split("\\.");
tv.setText(result + ": " + separated.length);
super.onPostExecute(result);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.