how to extract numeric values from input string in java

后端 未结 15 2036
说谎
说谎 2020-12-13 16:25

How can I extract only the numeric values from the input string?

For example, the input string may be like this:

String str=\"abc d 1234567890pqr 548         


        
15条回答
  •  孤城傲影
    2020-12-13 16:58

    If you do not want to use regex,

    String str = " abc d 1234567890pqr 54897";
    
    char[] chars = new char[str.length()];
    
    int i = 0;
    for (int j = 0; j < str.length(); j++) {
        char c = str.charAt(j);
        if (Character.isDigit(c)) {
            chars[i++] = c;
            if (j != chars.length - 1)
                continue;
        }
        if (chars[0] == '\0')
            continue;
        String num = new String(chars).trim();
        System.out.println(num);
        chars = new char[str.length()];
        i = 0;
    
    }
    

    Output : 1234567890 54897

提交回复
热议问题