Java - Split String by Number and Letters

前端 未结 10 1788
春和景丽
春和景丽 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:53

    You can use two patterns :

    • [0-9]
    • [a-zA-Z]

    Split twice by each of them.

    List letters = Arrays.asList(test.split("[0-9]"));
    List numbers = Arrays.asList(test.split("[a-zA-Z]"))
                .stream()
                .filter(s -> !s.equals(""))
                .collect(Collectors.toList());
    
    if(letters.size() != numbers.size()){
            numbers.add("1");
        }
    

提交回复
热议问题