So I have, for example, a string such as this C3H20IO
What I wanna do is split this string so I get the following:
Array1 = {C,H,I,O}
Ar
I suggest splitting by uppercase letter using zero-width lookahead regex (to extract items like C12, O2, Si), then split each item into element and its numeric weight:
List elements = new ArrayList<>();
List weights = new ArrayList<>();
String[] items = "C6H12Si6OH".split("(?=[A-Z])"); // [C6, H12, Si6, O, H]
for (String item : items) {
String[] pair = item.split("(?=[0-9])", 2); // e.g. H12 => [H, 12], O => [O]
elements.add(pair[0]);
weights.add(pair.length > 1 ? Integer.parseInt(pair[1]) : 1);
}
System.out.println(elements); // [C, H, Si, O, H]
System.out.println(weights); // [6, 12, 6, 1, 1]