Java - Split String by Number and Letters

前端 未结 10 1785
春和景丽
春和景丽 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<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]
    
    0 讨论(0)
  • 2020-12-05 20:53

    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
    
    0 讨论(0)
  • 2020-12-05 20:53

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-05 20:53

    You can use two patterns :

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

    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");
        }
    
    0 讨论(0)
提交回复
热议问题