Total Pageviews

2015/03/04

How to read characters in a string in java

Requirement
If I have a String "(預)     16,276.22"
I would like to parse this String and get "(預)     " and "16,276.22" separately.

How to do
Here is the sample code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
String str2 = "(預)     16,276.22";
String numericString = "";
String nonNumericString = "";

char[] str2Array = str2.toCharArray();
for (char c : str2Array) {
    // print each character
    System.out.println("character = " + c);
    if (StringUtils.isNumeric("" + c) || ",".equals("" + c) || ".".equals("" + c)) {
        numericString += "" + c;
    } else {
        nonNumericString += "" + c;
    }
}
// print numberic part
System.out.println("numericString = " + numericString);
// print non-numeric part
System.out.println("nonNumericString = " + nonNumericString);

debug message:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
character = (
character = 
character = )
character =  
character =  
character =  
character =  
character =  
character = 1
character = 6
character = ,
character = 2
character = 7
character = 6
character = .
character = 2
character = 2
numericString = 16,276.22
nonNumericString = ()     



No comments: