简体   繁体   中英

Java StringTokenizer

I have the following input (11,C) (5,) (7,AB) I need to split them into 2 part for each coordinates. So my intarray should have 11, 5, 7 and my letter array should have C,,AB

But when I try using stringtokenizer, I only get my intarray should have 11, 5, 7 and my letter array should have C,AB

Is there any way I could get the empty part of (5,)? Thank you.

Vector<String> points = new Vector<String> ();
String a = "(11,C) (5,) (7,AB)";
StringTokenizer st = new StringTokenizer(a, "(,)");
    while(st.hasMoreTokens()) {
        points.add(st.nextToken());
    }
}
System.out.println(points);
List <Integer> digits = new ArrayList <Integer> ();
List <String> letters = new ArrayList <String> ();
Matcher m = Pattern.compile ("\\((\\d+),(\\w*)\\)").matcher (string);
while (m.find ())
{
    digits.add (Integer.valueOf (m.group (1)));
    letters.add (m.group (2));
}

Must be like this

String[] values = a.split("\\) \\(");
String[][] result = new String[values.length][2];
for (int i = 0; i < values.length; i++) {
    values[i] = values[i].replaceAll("\\(|\\)", "") + " ";
    result[i] = values[i].split("\\,");  
    System.out.println(result[i][0] + " * " + result[i][1]);
}

result will contain coordinate pairs.

public static void main(String[] args) {
    String s = "(11,C), (5,) ,(7,AB)";
    ArrayList<String> name = new ArrayList<String>();
    ArrayList<Integer> number = new ArrayList<Integer>();

    int intIndex = 0, stringIndex = 0;
    String[] arr = s.split(",");
    for (int i = 0; i < arr.length; i++) {
        String ss = arr[i].replace("(", "");
        ss = ss.replace(")", "");
        boolean b = isNumeric(ss);
        // System.out.println( Arrays.toString(arr));
        if (b) {
            int num = Integer.valueOf(ss.trim()).intValue();
            number.add(num);
        } else
            name.add(ss);
    }

    System.out.println(name);
    System.out.println(number);

}



public static boolean isNumeric(String str) {
    try {
        double d = Double.parseDouble(str);
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}

Try this: I have slightly changed the input from "(11,C) (5,) (7,AB)" to "(11,C), (5,) ,(7,AB)" .

Output:

[C,  , AB]
[11, 5, 7]

Brutal coding, in raw level:

List<String> points = new ArrayList<String> ();
    String source= "(11,C) (5,) (7,AB)";
    StringTokenizer deleteLeft = new StringTokenizer(source, "(");
        while(deleteLeft.hasMoreTokens()) {
            StringTokenizer deleteRight = new StringTokenizer(deleteLeft.nextToken(), ")");
                points.add(deleteRight.nextToken());
        }
        System.out.println(points);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM