How do I get the numbers and alphabets from a string?

I'm trying to work out a way of splitting up a string in java that follows a pattern like so:

String a = "24ab4h";

The results from this should be the following:

st[0] = "24";
st[1] = "a";
st[2] = "b";
st[3] = "4";
st[4] = "h";

However, I'm completely stumped as to how I can achieve this. Please, can someone help me out? I have tried searching online for a similar problem, however, it's very difficult to phrase it correctly in a search.

Upvotes: 0

Views: 224

Answers (3)

hm1
hm1

Reputation: 186

 public static void main(String[] args) {

    /*
     * Stack stack = new Stack(5); stack.push("10"); stack.push("20");
     * stack.push("20"); stack.push("20"); stack.push("20");
     * stack.push("20"); stack.push("20"); stack.displayStack();
     */

    String a = "24ab4h";
    System.out.println(Arrays.deepToString(splitString(a)));

}

private static String[] splitString(String a) {

    char[] result = new char[a.length()];
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < a.length(); i++) {
        if (isNumber(a.charAt(i))) {
            if (i != 0 && !isNumber(a.charAt(i - 1)))
                sb.append(" ");
                sb.append(a.charAt(i));
        } else {
            sb.append(" ");
            sb.append(a.charAt(i));
        }
    }
    return sb.toString().split(" ");
}

private static boolean isNumber(char c) {
    try {
        Integer i = Integer.parseInt(String.valueOf(c));
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}

Upvotes: 0

azro
azro

Reputation: 54148

If you use a split() function you'll loose the elements which are used as delimiters so I think use a Pattern is better :

public static void main(String args[]) {

    Matcher m = Pattern.compile("\\d+|[a-zA-Z]").matcher("24ab4h");

    List<String> res = new ArrayList<>();

    while (m.find()) {
        res.add(m.group());
    }     
}

The pattern will detect all group of digits OR alpabet char alone, then it will add all into a List (better than array because you don't know the size)


If you really want an array at the end, 2 solutions for List<String> ->String[] :

  • String[] array = res.toArray(new String[res.size()]);

  • String[] array = res.stream().toArray(String[]::new);

Upvotes: 2

Aleksey Kurkov
Aleksey Kurkov

Reputation: 341

Try to process your String in a loop, char by char.

String a = "24ab4h"; 

If focused char (2) is number - check next char (4). If next char is also a number - continue scanning. If next char differs from number - save focused char (or focused char sequence, in this example it is - 24).

The same logic for alphabet chars.

Upvotes: 0

Related Questions