[Solved] how to create array from string in java with respective data items [closed]


You are using the * to separate “main items” but it can also be inside the main item.

Your requirements look odd, but lets assume for the sake of argument that you are getting your input data like this and you want to split it like you suggested.
That means that every * that is preceded by a number is a separator, but a * that is not preceded by a number is not.

You can achieve that using regular expressions: (with a positive look-behind expression (?<=expr)

    String str = "USA*2*Japan*8^2*India*5^4^2*Germany*5";
    List<String> lst = Arrays.asList(Pattern.compile("(?<=\\d)\\*").split(str));
    System.out.println(lst);

Prints:

[USA*2, Japan*8^2, India*5^4^2, Germany*5]

After further clarification in the comment below, it seems that the problem is more generic than the initial example; the question becomes:

How do I split a string on a separator, but only after 2 occurrences
of the separator.

Although it’s possible to do with a regex, it may be easier to do and understand in a for loop like this:

public static List<String> split(String str, char splitChar, int afterOccurrences) {
    List<String> lst = new ArrayList<>();
    int occurrencesSeen = 0;
    int start = 0;
    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if (ch == splitChar) {
            occurrencesSeen++;
            if (occurrencesSeen >= afterOccurrences) {
                lst.add(str.substring(start, i));
                start = i + 1;
                occurrencesSeen = 0;
            }
        }
    }
    if (start < str.length() - 1)
        lst.add(str.substring(start));
    return lst;
}

public static void main(String[] args) {
    String str = "USA*2*Japan*8^2*India*5^4^2*Germany*5";
    System.out.println(split(str, '*', 2));
}

This method also allows you to split after 3 or any other number of occurrences.

6

solved how to create array from string in java with respective data items [closed]