Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java converting a group of string to String Array Integer Array

Tags:

java

arrays

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class sourc {
public static void main(String[] args) {
        String name = null;
        Integer id = null;
        String strings = "one*10*two*11*three*12";
        StringTokenizer st2 = new StringTokenizer(strings, "*");
        while (st2.hasMoreElements()) {
            name = st2.nextElement().toString();
            id = Integer.parseInt(st2.nextElement().toString());
            String[] str = new String[]{name};
            List<String> al = new ArrayList<String>(Arrays.asList(str));
            System.out.println(al);
            ArrayList<Integer> arrli = new ArrayList<Integer>(id);
            arrli.add(id);
            System.out.println(arrli);
        }

}

i have output like

[one]

[10]

[two]

[11]

[three]

[12]

But i need output like

[one,two,three]

[10,11,12]

like image 914
Manoj Kumar Govindharaj Avatar asked Mar 10 '23 03:03

Manoj Kumar Govindharaj


1 Answers

You don't need a tokenizer here, rather you can just split the string using String#split() with some regex replacement logic.

String input = "one*10*two*11*three*12";
String[] words = input.replaceAll("\\d+\\*?", "")
                      .split("\\*");
String[] nums = input.replaceAll("[^0-9*]+\\*?", "")
                     .split("\\*");
like image 199
Tim Biegeleisen Avatar answered Apr 27 '23 10:04

Tim Biegeleisen