Description:
I have values of type double (eg 1.0, 1.5, 2.0, etc.) which I would like to split into two parts. On one hand I would like to have the number before the period (.) ( the unit ) and on the other hand I would like to separate the decimal (the number after the period).
I attach the JAVA code of what I am trying to do
1 double duracion_horas = 1.5; //Esto sería una hora y media
2 String Sduracion_horas = String.valueOf(duracion_horas);
3 String separador_total[] = Sduracion_horas.split(".");
4
5 Toast.makeText(context, separador_total_clase[1], Toast.LENGTH_SHORT).show();
When executing this code, I get an error which points to line number 5:
java.lang.ArrayIndexOutOfBoundsException: length=0; index=1
Ask:
What can this error be due to? I've never had a problem using split before.
I hope to solve this problem as soon as possible. Thank you for reading!!
There are characters for "special use" called metacharacters ,
(from this list the only one that would work without problem is
}
).If these are used directly to split a string they will not work properly, example:
Incorrect output:
these characters must be escaped preceding the "\" character, example:
Correct output:
The same in the case you expose using "
.
":Incorrect output:
You must define the escaped separator like this
\\.
:Correct output:
I suggest you use the method indicated in the answer Having problems using a character as a separator?
and you can call it like this:
example:
you would have as output an array with the desired elements:
The problem you have is that it
split
takes anregex
as an argument.In a
regex
dot means any character, so no idea what it might be trying to be taking to do the split.In order for
regex
the point to be literally a point, it must be escaped with\
.Now in java
\
it is also the escape character in aString
and therefore you have to escape it as well.In short, the instruction would look like: