java string delimiter, keeping delimiter in token

六月ゝ 毕业季﹏ 提交于 2019-12-02 07:11:46

问题


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

回答1:


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.




回答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



回答3:


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


来源:https://stackoverflow.com/questions/10564867/java-string-delimiter-keeping-delimiter-in-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!