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
An approach without REGEX
and data stored using ArrayList
:
String s = "C3H20IO";
char Chem = '-';
String val = "";
boolean isFisrt = true;
List<Character> chemList = new ArrayList<Character>();
List<Integer> weightList = new ArrayList<Integer>();
for (char c : s.toCharArray()) {
if (Character.isLetter(c)) {
if (!isFisrt) {
chemList.add(Chem);
weightList.add(Integer.valueOf(val.equals("") ? "1" : val));
val = "";
}
Chem = c;
} else if (Character.isDigit(c)) {
val += c;
}
isFisrt = false;
}
chemList.add(Chem);
weightList.add(Integer.valueOf(val.equals("") ? "1" : val));
System.out.println(chemList);
System.out.println(weightList);
OUTPUT:
[C, H, I, O]
[3, 20, 1, 1]
make (for loop) with size of input length and add following condition
if(i==number)
// add it to the number array
if(i==character)
//add it into character array
I did this as following
ArrayList<Integer> integerCharacters = new ArrayList();
ArrayList<String> stringCharacters = new ArrayList<>();
String value = "C3H20IO"; //Your value
String[] strSplitted = value.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); //Split numeric and strings
for(int i=0; i<strSplitted.length; i++){
if (Character.isLetter(strSplitted[i].charAt(0))){
stringCharacters.add(strSplitted[i]); //If string then add to strings array
}
else{
integerCharacters.add(Integer.parseInt(strSplitted[i])); //else add to integer array
}
}
You can use two patterns :
Split twice by each of them.
List<String> letters = Arrays.asList(test.split("[0-9]"));
List<String> numbers = Arrays.asList(test.split("[a-zA-Z]"))
.stream()
.filter(s -> !s.equals(""))
.collect(Collectors.toList());
if(letters.size() != numbers.size()){
numbers.add("1");
}