Java - Split String by Number and Letters

前端 未结 10 1802
春和景丽
春和景丽 2020-12-05 20:14

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         


        
10条回答
  •  生来不讨喜
    2020-12-05 20:52

    An approach without REGEX and data stored using ArrayList:

    String s = "C3H20IO";
    
    char Chem = '-';
    String val = "";
    boolean isFisrt = true;
    List chemList = new ArrayList();
    List weightList = new ArrayList();
    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]
    

提交回复
热议问题