0

I need to be able to break apart a string into its letters and its numbers. The strings it will be looking at are something along the lines of

"dir1" "path11"

I will also need to temporarily store the 2 values. I have found the .split method and it looks like it could be what I'm after but I can't figure out how to use it, should I keep looking into it or is there a better way?

H. Brown
  • 3
  • 3
  • Are the strings always **alphabetic characters followed by digits**? – Naveed S Dec 04 '16 at 17:47
  • In this case they will be – H. Brown Dec 04 '16 at 17:48
  • Here is similar solution on SO http://stackoverflow.com/questions/8270784/how-to-split-a-string-between-letters-and-digits-or-between-digits-and-letters or http://stackoverflow.com/questions/16787099/how-to-split-the-string-into-string-and-integer-in-java – dkb Dec 04 '16 at 17:59

2 Answers2

0

Use String.split() as in

String[] strings = "abc111".split("(?=\\d+)(?<=\\D+)");

The split() function takes a regex around which the string will be split up.

Here the pattern has two assertions: one which asserts that the characters ahead are digits alone and another one which asserts that the preceding characters are non-digits. So it will split just after the end of non-digits (which is just before the beginning of digits).

Naveed S
  • 5,106
  • 4
  • 34
  • 52
0

Regex and split can help to do that:

public static void main(String[] args) {
String[] c = "path11".split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
System.out.println(Arrays.toString(c));
}

output=

[path, 11]

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97