Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to get a substring from a java string Tokenizer

I need to get a substring from a java string tokenizer.

My inpunt string is = Pizza-1*Nutella-20*Chicken-65*

        StringTokenizer productsTokenizer = new StringTokenizer("Pizza-1*Nutella-20*Chicken-65*", "*");
        do
        {
            try
            {
                int pos = productsTokenizer .nextToken().indexOf("-");
                String product = productsTokenizer .nextToken().substring(0, pos+1);
                String count= productsTokenizer .nextToken().substring(pos, pos+1);
                System.out.println(product + "   " + count);
            }
            catch(Exception e)
            {

            }
        }
        while(productsTokenizer .hasMoreTokens());

My output must be:

Pizza  1
Nutella  20
Chicken  65

I need the product value and the count value in separate variables to insert that values in the Data Base.

I hope you can help me.

like image 502
darthlitox Avatar asked Nov 29 '25 06:11

darthlitox


1 Answers

You could use String.split() as

String[] products = "Pizza-1*Nutella-20*Chicken-65*".split("\\*");

for (String product : products) {
    String[] prodNameCount = product.split("\\-");
    System.out.println(prodNameCount[0] + " " + prodNameCount[1]);
}

Output

Pizza  1
Nutella  20
Chicken  65
like image 65
Ravi K Thapliyal Avatar answered Nov 30 '25 20:11

Ravi K Thapliyal