Split in Java, how to detect that there is no separator


I am separating a word in Java whose separator is a -, my problem comes in that sometimes it does not have - to separate and therefore it gives me an error, as I could previously detect that the separator does not exist. An example to be understood: That is, it works correctly

String palabra="hola-adios";

But if I pass through the Split a string without a separator like the following, there is an exception:

String palabra2="hola";
asked by Silvia 29.04.2018 в 00:46

2 answers


Use the contains() method of the String class that lets you know if a string contains another within.

if (palabla.contains("-")) {
    // Aplicas el split
answered by 29.04.2018 / 00:52

Strings in java have a method called contains, which returns a Boolean value if the string contains another ...

You can use it this way:

if (palabra.contains("-")) {
    String[] identificador = palabra.split("-");
    // Lo que deses hacer con eso
answered by 29.04.2018 в 00:54