Extract digits from string - StringUtils Java

前端 未结 18 1231
忘掉有多难
忘掉有多难 2020-12-01 09:06

I have a String and I want to extract the (only) sequence of digits in the string.

Example: helloThisIsA1234Sample. I want the 1234

It\'s a given that the s

18条回答
  •  感动是毒
    2020-12-01 09:27

    A very simple solution, if separated by comma or if not separated by comma

    public static void main(String[] args) {
    
        String input = "a,1,b,2,c,3,d,4";
        input = input.replaceAll(",", "");
    
        String alpha ="";
        String num = "";
    
        char[] c_arr = input.toCharArray();
    
        for(char c: c_arr) {
            if(Character.isDigit(c)) {
                alpha = alpha + c;
            }
            else {
                num = num+c;
            }
        }
    
        System.out.println("Alphabet: "+ alpha);
        System.out.println("num: "+ num);
    
    }
    

提交回复
热议问题