Extract Integer Part in String

后端 未结 8 2119
灰色年华
灰色年华 2020-11-27 06:38

What is the best way to extract the integer part of a string like

Hello123

How do you get the 123 part. You can sort of hack it using Java\

8条回答
  •  一生所求
    2020-11-27 06:44

    Although I know that it's a 6 year old question, but I am posting an answer for those who want to avoid learning regex right now(which you should btw). This approach also gives the number in between the digits(for eg. HP123KT567 will return 123567)

        Scanner scan = new Scanner(new InputStreamReader(System.in));
        System.out.print("Enter alphaNumeric: ");
        String x = scan.next();
        String numStr = "";
        int num;
    
        for (int i = 0; i < x.length(); i++) {
            char charCheck = x.charAt(i);
            if(Character.isDigit(charCheck)) {
                numStr += charCheck;
            }
        }
    
        num = Integer.parseInt(numStr);
        System.out.println("The extracted number is: " + num);
    

提交回复
热议问题