http://www.technicalpage.net/search/label/SQL

Separate number, characters and special characters And get the sum of the numbers.

 Separate number, characters and special characters 

And get the sum of the numbers.

package test;

 

import java.util.Arrays;

 

public class SeparateCharAndInteger {

 

       public static void main(String[] args) { // we use regular expression

 

             String str = "asd?&&*$#^&)123As?@jsH76>10]aa##)*";

 

             String numberOnly = str.replaceAll("[^0-9]", "");

             String stringOnly = str.replaceAll("[^a-zA-Z]", "");

             String specialCharOnly = str.replaceAll("[a-zA-Z0-9]", ""); // there is no cap here ^^^^

 

             System.out.println("number only: " + numberOnly);// Output: 1237610

             System.out.println("string only: " + stringOnly);// Output: asdAsjsHaa

             System.out.println("special Character Only only: " + specialCharOnly);// Output: ?&&*$#^&)?@>]##)*

 

             // ------------------Get the sum of the numbers-------------------

             String numberArray = str.replaceAll("[^0-9]", " ");// numbers with space

             System.out.println("special Character Only only: " + numberArray);// Output: 123 76 10

             String ar = numberArray.trim();

 

             System.out.println("ar: " + ar);// Output After TRIM:123 76 10

             String[] strNumArr = ar.split(" ");// Creating Array

             System.out.println(Arrays.toString(strNumArr));// Output: [123, , , , , , , 76, 10]

             int sum = 0;

             for (int i = 0; i < strNumArr.length; i++) {

                    if (!(strNumArr[i].equals(""))) {// this is not space(" ") but without space("")--this is important

                           System.out.println("strNumArr[i]: " + strNumArr[i]);// Output123, 76, 10

                           sum = sum + Integer.parseInt(strNumArr[i]);

                    }

             }

             System.out.println("The sum: " + sum);// Output: 209

       }

}

 

No comments:

Post a Comment