1

im trying to split a string but keep the delimiter at the beginning of the next token (if thats possible)

Example: I'm trying to split the string F120LF120L into

F120
L
F120
L

I've tried

StringTokenizer st = new StringTokenizer(str, "F,L");

but that just returns

120
120
Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
rod
  • 13
  • 1
  • 3

3 Answers3

2

Use split(), for all practical purposes StringTokenizer is deprecated (it's still there only for backwards compatibility). This will work:

String delimiter = "L";
String str = "F120LF120L";
String[] splitted = str.split(delimiter);

for (String s : splitted) {
    System.out.println(s);
    System.out.println(delimiter);
}

> F120
> L
> F120
> L
Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
2

From the docs, you can use StringTokenizer st = new StringTokenizer(str, "L", true); The last parameter is a boolean that specifies that delimiters have to be returned too.

S.R.I
  • 1,860
  • 14
  • 31
  • That way, F is returned separately.. not F120! For his example, the following would work: StringTokenizer st = new StringTokenizer(str, "L", true); – Javaguru May 12 '12 at 15:21
  • Ah, yes. Should read more carefully. :( I'll update the answer, thanks! – S.R.I May 12 '12 at 15:25
  • BTW, note to the OP, if you're splitting by tokesn, you don't need the last parameter either. That is, you're just using "L" as a token, not "F" – S.R.I May 12 '12 at 15:27
  • yeah i will be using "F" as a token, also sometimes there will be some numbers after "L" but thanks, im on the right track now to figure the rest out myself (I hope) :-) – rod May 12 '12 at 15:57
0

How about doing it brute force?

String del = "L";
String str = "F120LLF120LLLLF12L";
int i = 0;

while (true) {
    i = str.indexOf(del, i);
    if (i == -1) break;
    String a = str.substring(0, i);
    String b = str.substring(i + del.length());
    str = a + " " + del;
    str += b.startsWith(del) || b.length() == 0 ? b : " " + b;
    i = a.length() + del.length() + 1;
}

System.out.println(str);
// Will print: F120 L L F120 L L L L F12 L
tor
  • 636
  • 3
  • 7
  • 18