java string delimiter, keeping delimiter in token

前端 未结 3 461
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 00:06

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

3条回答
  •  春和景丽
    2021-01-26 00:33

    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
    

提交回复
热议问题