Use more than one delimiter with StringTokenizer

1

I would like to know how I could in java eclipse using the StringTokenizer class to declare more than 1 delimiter so that I can separate the String in tokes. Thanks in advance

    
asked by ivaaan 14.04.2018 в 23:29
source

1 answer

0

As commented by @Juan, for that you need to use split and include regular expressions (Regex). An example would be:

String [] tokens = stringCualquiera.split("-|\.");

I leave a link to the official documentation on StringTokenizer .

I leave you a clearer example, but once you have the foundation, testing is very simple and the best way to learn (reading and testing). I leave you a couple of examples, if you look at regular expressions you can make the combinations you want. If you want to separate with '.' and ',':

public class MyClass {
    public static void main(String args[]) {

        String stringCualquiera = "Pues es como decir, por poner un ejemplo, que se delimitan con puntos. Y tambien valen las comas y los letras a y b";
        String [] tokens = stringCualquiera.split("[,.]");


        for (int i = 0; i <= tokens.length-1; i++) {
        System.out.println(tokens[i]);
        }
    }
}

Print:

Pues es como decir
 por poner un ejemplo
 que se delimitan con puntos
 Y tambien valen las comas y los letras a y b

And if you want the delimiter to be either a ',' as 'an' or an 'e'.

public class MyClass {
    public static void main(String args[]) {

        String stringCualquiera = "Pues es como decir, por poner un ejemplo, que se delimitan con puntos. Y tambien valen las comas y los letras a y b";
        String [] tokens = stringCualquiera.split("[,ae]");


        for (int i = 0; i <= tokens.length-1; i++) {
        System.out.println(tokens[i]);
        }
    }
}

What it would print:

Pu
s 
s como d
cir
 por pon
r un 
j
mplo
 qu
 s
 d
limit
n con puntos. Y t
mbi
n v
l
n l
s com
s y los l
tr
s 
 y b

If you want to look at regular expressions in Java, you can do it here .

    
answered by 15.04.2018 в 01:56